package com.ybkj.daijia.server.service.impl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ybkj.daijia.InfoFeeType;
import com.ybkj.daijia.OrderNumberConfig;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.serverUtils.UseAllDataUtil;
import com.ybkj.daijia.api.util.ErrorConstantV4;
import com.ybkj.daijia.chart.TableOrderMonthVo;
import com.ybkj.daijia.common.CompanyOrderVo;
import com.ybkj.daijia.common.DriverOrderDetailVo;
import com.ybkj.daijia.common.DriverOrderVo;
import com.ybkj.daijia.common.MemberOrderVo;
import com.ybkj.daijia.common.OrderFromSourceVo;
import com.ybkj.daijia.common.PageVo;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.config.FreightApi;
import com.ybkj.daijia.config.PassengerApi;
import com.ybkj.daijia.config.SalesApi;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.OrderRevokeTimerTask;
import com.ybkj.daijia.server.event.model.ActivityCheckEvent;
import com.ybkj.daijia.server.event.model.MemberConsumedEvent;
import com.ybkj.daijia.server.event.model.freight.FreightOrderCallBackEvent;
import com.ybkj.daijia.server.event.model.freight.FreightOrderFinishEvent;
import com.ybkj.daijia.server.freight.Order;
import com.ybkj.daijia.server.freight.Order.PayTypeDetails;
import com.ybkj.daijia.server.freight.OrderMemo;
import com.ybkj.daijia.server.freight.OrderOrbit;
import com.ybkj.daijia.server.freight.OrderReview;
import com.ybkj.daijia.server.freight.OrderStatus;
import com.ybkj.daijia.server.freight.PayRecordOrder;
import com.ybkj.daijia.server.freight.Truck;
import com.ybkj.daijia.server.freight.TruckType;
import com.ybkj.daijia.server.freight.TruckTypeCompany;
import com.ybkj.daijia.server.mapper.AreaMapper;
import com.ybkj.daijia.server.mapper.CompanyMapper;
import com.ybkj.daijia.server.mapper.DriverChoseLevelFreightMapper;
import com.ybkj.daijia.server.mapper.DriverLevelDetailMapper;
import com.ybkj.daijia.server.mapper.DriverLevelMapper;
import com.ybkj.daijia.server.mapper.DriverLevelMoneyTimeDetailMapper;
import com.ybkj.daijia.server.mapper.DriverMapper;
import com.ybkj.daijia.server.mapper.DriverPaymentsRecordMapper;
import com.ybkj.daijia.server.mapper.FinancialRecordMapper;
import com.ybkj.daijia.server.mapper.FirstOrderPassengerMapper;
import com.ybkj.daijia.server.mc.Enterprise;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.mc.PassengerAccount;
import com.ybkj.daijia.server.model.Area;
import com.ybkj.daijia.server.model.ChartDay;
import com.ybkj.daijia.server.model.ChartMonth;
import com.ybkj.daijia.server.model.ChartYear;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverChoseLevelFreight;
import com.ybkj.daijia.server.model.DriverLevel;
import com.ybkj.daijia.server.model.DriverLevel.TimePoint;
import com.ybkj.daijia.server.model.DriverLevelDetail;
import com.ybkj.daijia.server.model.DriverLevelDetail.DriverLevelType;
import com.ybkj.daijia.server.model.DriverLevelMoneyDetail;
import com.ybkj.daijia.server.model.DriverLevelMoneyDetail.DriverLevelMoneyType;
import com.ybkj.daijia.server.model.DriverLevelMoneyTimeDetail;
import com.ybkj.daijia.server.model.DriverPaymentsRecord;
import com.ybkj.daijia.server.model.FinancialRecord;
import com.ybkj.daijia.server.model.FirstOrderPassenger;
import com.ybkj.daijia.server.model.Rate;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.sales.Activity.ActivityEvent;
import com.ybkj.daijia.server.sales.Activity.OrderType;
import com.ybkj.daijia.server.sales.Coupon;
import com.ybkj.daijia.server.sales.CouponRule;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.FreightService;
import com.ybkj.daijia.server.service.SmsService;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;

@Service
public class DefaultFreightService implements FreightService {

    private static final Logger logger = LoggerFactory.getLogger(DefaultFreightService.class);
    @Autowired
    private FreightApi freightApi;
    @Autowired
    private PassengerApi passengerApi;
    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private DriverService driverService;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private FinancialRecordMapper financialRecordMapper;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;
    @Autowired
    private DriverLevelDetailMapper driverLevelDetailMapper;
    @Autowired
    private DriverChoseLevelFreightMapper driverChoseLevelFreightMapper;
    @Autowired
    private DriverLevelMapper driverLevelMapper;
    @Autowired
    private DriverLevelMoneyTimeDetailMapper driverLevelMoneyTimeDetailMapper;
    @Autowired
    private DriverPaymentsRecordMapper driverPaymentsRecordMapper;
    @Autowired
    private FirstOrderPassengerMapper firstOrderPassengerMapper;
    @Autowired
    private SalesApi salesApi;
    @Autowired
    private SmsService smsService;


    @Override
    public Page<TruckType> queryTruckType(Long companyId) {
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.QUERY_TRUCKTYPE)
            .append("?appKey={appKey}&page={page}&rows={rows}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));
        if (companyId != null && companyId != 0) {
            kv.put("companyId", String.valueOf(companyId));
            builder.append("&companyId={companyId}");
        }
        List<TruckType> list = new ArrayList<TruckType>();
        long total = 0;
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<TruckType>>() {
                }.getType());
                for (TruckType truckType : list) {
                    Area area = areaMapper.selectByPrimaryKeyWithCharge(truckType.getAreaId());
                    if (area != null) {
                        truckType.setAreaName(area.getName());
                    }
                }
            }
        }
        return new PageImpl<TruckType>(list, pageable, total);
    }

    @Override
    public TruckType findByTruckTypeId(Long truckTypeId) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.QUERY_ONE_TRUCKTYPE)
            .append(".json?appKey={appKey}&truckTypeId={truckTypeId}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("truckTypeId", String.valueOf(truckTypeId));
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        TruckType truckType = null;
        if (result != null) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                truckType = gson.fromJson(data.toString(), new TypeToken<TruckType>() {
                }.getType());
                Area area = areaMapper.selectByPrimaryKeyWithCharge(truckType.getAreaId());
                if (area != null) {
                    truckType.setAreaName(area.getName());
                }
            }
        }
        return truckType;
    }

    public String updateTruckType(Long truckTypeId, String typeName,
        Double len, Double width, Double height, Double carryingCapacity,
        Integer sequence, Boolean cangointotown, Long areaId) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.UPDATE_TRUCKTYPE)
            .append("?appKey={appKey}&truckTypeId={truckTypeId}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("truckTypeId", String.valueOf(truckTypeId));
        if (StringUtils.isNotBlank(typeName)) {
            builder.append("&typeName={typeName}");
            kv.put("typeName", typeName);
        }
        if (len != null) {
            builder.append("&len={len}");
            kv.put("len", String.valueOf(len));
        }
        if (width != null) {
            builder.append("&width={width}");
            kv.put("width", String.valueOf(width));
        }
        if (height != null) {
            builder.append("&height={height}");
            kv.put("height", String.valueOf(height));
        }
        if (carryingCapacity != null) {
            builder.append("&carryingCapacity={carryingCapacity}");
            kv.put("carryingCapacity", String.valueOf(carryingCapacity));
        }
        if (sequence != null) {
            builder.append("&sequence={sequence}");
            kv.put("sequence", String.valueOf(sequence));
        }
        if (areaId != null) {
            builder.append("&areaId={areaId}");
            kv.put("areaId", String.valueOf(areaId));
        }
        if (cangointotown != null) {
            builder.append("&cangointotown={cangointotown}");
            kv.put("cangointotown", String.valueOf(cangointotown));
        }
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        String message = null;
        if (result != null) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                message = jo.getString("message");
            } else {
                message = jo.getString("message");
            }
        }
        return message;
    }

    @Override
    public Page<Order> queryFreightOrder(Long companyId, String orderNo,
        String employName, String employPhone, String passengerName,
        String passengerPhone, String truckType, Integer status) {
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.QUERY_ORDER)
            .append("?appKey={appKey}&page={page}&rows={rows}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));
        kv.put("orderby", "id desc");
        builder.append("&orderby={orderby}");
        if (companyId != null) {
            kv.put("companyId", String.valueOf(companyId));
            builder.append("&companyId={companyId}");
        }

        if (StringUtils.isNotBlank(orderNo)) {
            kv.put("orderNo", orderNo);
            builder.append("&orderNo={orderNo}");
        }
        if (StringUtils.isNotBlank(employName)) {
            kv.put("employName", employName);
            builder.append("&employName={employName}");
        }
        if (StringUtils.isNotBlank(employPhone)) {
            kv.put("employPhone", employPhone);
            builder.append("&employPhone={employPhone}");
        }
        if (StringUtils.isNotBlank(passengerName)) {
            kv.put("passengerName", passengerName);
            builder.append("&passengerName={passengerName}");
        }
        if (StringUtils.isNotBlank(passengerPhone)) {
            kv.put("passengerPhone", passengerPhone);
            builder.append("&passengerPhone={passengerPhone}");
        }
        if (StringUtils.isNotBlank(truckType)) {
            kv.put("truckType", truckType);
            builder.append("&truckType={truckType}");
        }
        if (status != null && status != -1) {
            kv.put("status", String.valueOf(status));
            builder.append("&status={status}");
        }
        List<Order> list = new ArrayList<Order>();
        long total = 0;
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Order>>() {
                }.getType());
                for (Order order : list) {
                    String memo = "";
                    List<OrderMemo> orderMemos = order.getOrderMemos();
                    for (int i = 0; i < orderMemos.size(); i++) {
                        memo += ((i + 1) + ":");
                        memo += orderMemos.get(i).getMemo() + "\n";
                    }

                    order.setMemo(memo);

                }
            }

        }
        return new PageImpl<Order>(list, pageable, total);
    }

    public String deleteTruckType(Long truckTypeId) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.NEW_DELETE_TRUCKTYPE)
            .append("?appKey={appKey}&truckTypeId={truckTypeId}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("truckTypeId", String.valueOf(truckTypeId));
        String result = freightApi.post(builder.toString(), kv, settingUtils.get());
        String message = null;
        if (StringUtils.isNotBlank(result)) {
            JSONObject jo = new JSONObject(result);
            int code = jo.getInt("code");
            if (code == 0) {
                message = "删除成功";
            } else {
                message = jo.getString("message");
            }
        }
        return message;
    }

    @Override
    public Result<TruckType> createTruckType(TruckType truckType) {
        StringBuilder builder = new StringBuilder();
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.CREATE_TRUCKTYPE)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        builder.append("&typeName={typeName}");
        builder.append("&len={len}");
        builder.append("&width={width}");
        builder.append("&height={height}");
        builder.append("&carryingCapacity={carryingCapacity}");
        builder.append("&cangointotown={cangointotown}");
        builder.append("&areaId={areaId}");
        builder.append("&sequence={sequence}");
        builder.append("&companyId={companyId}");
        builder.append("&companyName={companyName}");
        if (principal.isCompanyType()) {
            kv.put("companyId", String.valueOf(truckType.getCompanyId()));
            kv.put("companyName", String.valueOf(truckType.getCompanyName()));
        } else {
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            kv.put("companyName", principal.getCompanyAbbreviation());
        }

        kv.put("typeName", truckType.getTypeName());
        kv.put("len", String.valueOf(truckType.getLen()));
        kv.put("width", String.valueOf(truckType.getWidth()));
        kv.put("height", String.valueOf(truckType.getHeight()));
        kv.put("carryingCapacity", String.valueOf(truckType.getCarryingCapacity()));
        kv.put("cangointotown", String.valueOf(truckType.getCangointotown()));
        kv.put("areaId", String.valueOf(truckType.getAreaId()));
        kv.put("sequence", String.valueOf(truckType.getSequence()));
        String result = freightApi.post(builder.toString(), kv, settingUtils.get());
        Result<TruckType> resultTruckType = new Result<TruckType>();
        if (result != null) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                truckType = gson.fromJson(data.toString(), new TypeToken<TruckType>() {
                }.getType());
                Area area = areaMapper.selectByPrimaryKey(truckType.getAreaId());
                truckType.setAreaName(area.getName());
                resultTruckType.setResult(truckType);
                resultTruckType.setSuccess(true);
                resultTruckType.setMessage("创建货车类型成功");
            } else {
                resultTruckType.setSuccess(false);
                String msg = jo.getString("message");
                resultTruckType
                    .setMessage(msg.split(":").length > 1 ? msg.split(":")[1] : msg.split(":")[0]);
            }
        }
        return resultTruckType;
    }

    @Override
    public List<TruckType> queryTruckTypes(Long companyId) {
        List<TruckType> list = new ArrayList<TruckType>();

        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.NEW_QUERY_TRUCKTYPE)
            .append("?appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();
        if (companyId != null && companyId != 0) {
            kv.put("companyId", String.valueOf(companyId));
            builder.append("&companyId={companyId}");
        }
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                list = gson.fromJson(ja.toString(), new TypeToken<List<TruckType>>() {
                }.getType());
                for (TruckType truckType : list) {
                    Area area = areaMapper.selectByPrimaryKeyWithCharge(truckType.getAreaId());
                    if (area != null) {
                        truckType.setAreaName(area.getName());
                    }

                }
            }
        }
        return list;

    }

    @Override
    public Result<Order> createOrder(Long passengerId, String passengerName,
        String passengerPhone, Long companyId, String companyName,
        Long truckTypeId, String truckTypeName, String channelName, Long startTime,
        String memo, Boolean flitting, Boolean receipt,
        Boolean receivedPay, Double payMount, Double startPrice,
        Double mileage, Integer runTime, Double mileagePrice,
        Double runTimePrice, Long couponId, Double couponMoney, Double budgetPay,
        String waypoint, String operator, Boolean fixedPrice, Double fixPriceMoney) {
        Result<Order> r = new Result<Order>();
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        Passenger passenger = new Passenger();

        if (passengerId == null) {
            passenger.setName(passengerName);
            passenger.setPhone(passengerPhone);
            passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_PHONE);
            passenger.setType(Passenger.TYPE_PASSENGER);
            passenger.setAllowOverdraw(false);
            if (principal.isCompanyType()) {
                passenger.setCompanyId(companyId);
                passenger.setCompanyName(companyName);
            } else {
                passenger.setCompanyId(principal.getCompanyId());
                passenger.setCompanyName(principal.getCompanyAbbreviation());
            }

            Result<Passenger> result = passengerApi.createPersonal(passenger, settingUtils.get());
            passenger = result.getResult();
            if (!result.isSuccess()) {
                r.setMessage("创建新乘客失败!");
                r.setSuccess(false);
                return r;
            }
        } else {
            passenger.setId(passengerId);
            passenger.setName(passengerName);
            passenger.setPhone(passengerPhone);
        }

        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.CREATE_ORDER)
            .append("?appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("passengerId", String.valueOf(passenger.getId()));
        builder.append("&passengerId={passengerId}");
        kv.put("operator", operator);
        builder.append("&operator={operator}");
        kv.put("passengerName", passenger.getName());
        builder.append("&passengerName={passengerName}");
        kv.put("passengerPhone", passenger.getPhone());
        builder.append("&passengerPhone={passengerPhone}");
        if (principal.isCompanyType()) {
            kv.put("companyId", String.valueOf(companyId));
            builder.append("&companyId={companyId}");
            kv.put("companyName", companyName);
            builder.append("&companyName={companyName}");
        } else {
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            builder.append("&companyId={companyId}");
            kv.put("companyName", principal.getCompanyAbbreviation());
            builder.append("&companyName={companyName}");
        }

        kv.put("truckTypeId", String.valueOf(truckTypeId));
        builder.append("&truckTypeId={truckTypeId}");
        kv.put("truckTypeName", truckTypeName);
        builder.append("&truckTypeName={truckTypeName}");
        kv.put("channelName", Order.ORDER_TYPE_PHONE);
        builder.append("&channelName={channelName}");
        kv.put("startTime", String.valueOf(startTime));
        builder.append("&startTime={startTime}");
        if (StringUtils.isNotBlank(memo)) {
            kv.put("memo", memo);
            builder.append("&memo={memo}");
        }
        if (flitting != null && flitting.booleanValue()) {
            kv.put("flitting", String.valueOf(flitting));
            builder.append("&flitting={flitting}");
        }
        if (receipt != null && receipt.booleanValue()) {
            kv.put("receipt", String.valueOf(receipt));
            builder.append("&receipt={receipt}");
        }
        if (receivedPay != null && receivedPay.booleanValue()) {
            kv.put("receivedPay", String.valueOf(receivedPay));
            builder.append("&receivedPay={receivedPay}");
        }
        if (payMount != null && receivedPay != null && receivedPay.booleanValue()) {
            kv.put("payMount", String.valueOf(payMount));
            builder.append("&payMount={payMount}");
        }
        if (startPrice != null) {
            kv.put("preStartPrice", String.valueOf(startPrice));
            builder.append("&preStartPrice={preStartPrice}");
        }
        if (mileage != null) {
            kv.put("preMileage", String.valueOf(mileage));
            builder.append("&preMileage={preMileage}");
        }
        if (runTime != null) {
            kv.put("preRunTime", String.valueOf(runTime));
            builder.append("&preRunTime={preRunTime}");
        }

        if (mileagePrice != null) {
            kv.put("preMileagePrice", String.valueOf(mileagePrice));
            builder.append("&preMileagePrice={preMileagePrice}");
        }
        if (runTimePrice != null) {
            kv.put("preRunTimePrice", String.valueOf(runTimePrice));
            builder.append("&preRunTimePrice={preRunTimePrice}");
        }

        if (couponMoney != null) {
            kv.put("couponMoney", String.valueOf(couponMoney));
            builder.append("&couponMoney={couponMoney}");
        }

        if (couponId != null) {
            kv.put("couponId", String.valueOf(couponId));
            builder.append("&couponId={couponId}");
        }

        if (budgetPay != null) {
            kv.put("budgetPay", String.valueOf(budgetPay));
            builder.append("&budgetPay={budgetPay}");
        }

        if (StringUtils.isNotBlank(waypoint)) {
            kv.put("waypoint", waypoint);
            builder.append("&waypoint={waypoint}");
        }

        if (fixedPrice != null) {
            kv.put("fixPrice", String.valueOf(fixedPrice));
            builder.append("&fixPrice={fixPrice}");
        }

        if (fixPriceMoney != null) {
            kv.put("fixPriceMoney", String.valueOf(fixPriceMoney));
            builder.append("&fixPriceMoney={fixPriceMoney}");
        }

        String result = freightApi.post(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                Order o = gson.fromJson(data.toString(), Order.class);
                r.setResult(o);
                r.setSuccess(true);
            } else {
                String message = jo.getString("message");
                r.setMessage(message);
                r.setSuccess(false);
            }
        }
        return r;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Order> cancelOrder(Order order, Driver driver, String cancelCause) {
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();
        String operator;
        if (principal == null) {
            operator = "后台系统";
        } else {
            operator = principal.getUsername();
        }
        Result<Order> result = new Result<Order>();
        result.setSuccess(false);
        result.setMessage("销单失败");
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.CANCEL_ORDER).append(
            "?orderId={orderId}&action={action}&operator={operator}&cause={cause}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("orderId", String.valueOf(order.getId()));
        kv.put("action", "cancel");
        kv.put("cause", cancelCause);
        kv.put("operator", operator);

        String resultStr = freightApi.put(builder.toString(), kv, settingUtils.get());
        if (StringUtils.isBlank(resultStr)) {
            result.setSuccess(true);
            result.setMessage("销单成功");

            if (null != driver) {
                if (driver.getStatus() != Driver.DRIVER_OFFLINE) {
                    driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_ONLINE, null,
                        driver.getId());
                }
            }

            //销单退款
            if (null != order.getPrePayTypeDetail() && !order.getPrePayTypeDetail()
                .equals(PayTypeDetails.coupon)) {
                Result<Passenger> result_p = passengerApi
                    .findOnePassenger(order.getPassengerId(), settingUtils.get());
                Passenger passenger = result_p.getResult();
                if (null != passenger) {
                    BigDecimal coupon_hasPayed = BigDecimal.ZERO;
                    if (null != order.getCouponId()) {
                        Coupon coupon = salesApi.findOneCoupon(order.getCouponId()).getResult();
                        if (null != coupon) {
                            if (coupon.getCouponRule().getType()
                                .equals(CouponRule.TYPE_DEDUCTION)) {
                                coupon_hasPayed = coupon.getCouponRule().getMoney();
                            } else if (coupon.getCouponRule().getType()
                                .equals(CouponRule.TYPE_DISCOUNT)) {
                                Double discount = coupon.getCouponRule().getDiscount();
                                coupon_hasPayed = new BigDecimal(order.getBudgetPay()).multiply(
                                    new BigDecimal(1).subtract(
                                        new BigDecimal(discount).divide(new BigDecimal(10))))
                                    .setScale(0, BigDecimal.ROUND_DOWN);
                            }
                        }
                    }
                    BigDecimal tuikuan = new BigDecimal(order.getBudgetPay())
                        .subtract(coupon_hasPayed);
                    if (tuikuan.doubleValue() > 0) {
                        if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                            passengerApi.createPassengerAccount(passenger, null, tuikuan,
                                PassengerAccount.PayType.RECHARGE_TYPE_CANCEL_RETURN,
                                PassengerAccount.OPERATING_SYS, "销单退款:" + cancelCause,
                                order.getId(), order.getOrderNo(),
                                PassengerAccount.ORDER_TYPE_FREIGHT, null, true, false,
                                settingUtils.get());
                        } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                            Enterprise enterprise = passengerApi
                                .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get())
                                .getResult();
                            if (null != enterprise) {
                                passengerApi.createEnterpriseAccount(enterprise, tuikuan,
                                    PassengerAccount.PayType.RECHARGE_TYPE_CANCEL_RETURN,
                                    PassengerAccount.OPERATING_SYS, "销单退款:" + cancelCause,
                                    order.getId(), order.getOrderNo(),
                                    PassengerAccount.ORDER_TYPE_FREIGHT, null, true, false,
                                    settingUtils.get());
                            }
                        }
                    }

                }
            }
        }
        return result;
    }

    @Override
    public Order findOne(Long id) {
        Order order = null;
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.QUERY_ORDER_ONE)
            .append("?orderId={orderId}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("orderId", String.valueOf(id));
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                order = gson.fromJson(data.toString(), Order.class);
            }
        }
        return order;
    }


    @Override
    public void remark(Long orderId, String memo) {
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();
        String operator = principal.getUsername();

        StringBuilder sb = new StringBuilder();
        sb.append(freightApi.getFreightBaseURL()).append(FreightApi.CREATE_ORDERMEMO)
            .append("?orderId={orderId}&memo={memo}&operator={operator}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("orderId", String.valueOf(orderId));
        kv.put("memo", memo);
        kv.put("operator", operator);

        String result = freightApi.post(sb.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code != 0) {
                throw new RuntimeException();
            }
        }
    }


    @Override
    public List<Order> selectCuidan() {
        List<Order> list = new ArrayList<Order>();

        StringBuilder sb = new StringBuilder();
        sb.append(freightApi.getFreightBaseURL()).append(FreightApi.QUERY_CUIDAN)
            .append("?appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();

        String result = freightApi.get(sb.toString(), kv, settingUtils.get());

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray ja = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                list = gson.fromJson(ja.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
        }
        return list;
    }

    @Override
    public void closeCuidan(Long orderId) {

        StringBuilder sb = new StringBuilder();
        sb.append(freightApi.getFreightBaseURL()).append(FreightApi.CLOSE_CUIDAN)
            .append("?appKey={appKey}");
        sb.append("&orderId={orderId}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("orderId", String.valueOf(orderId));

        freightApi.put(sb.toString(), kv, settingUtils.get());

    }

    @Override
    public Page<Map<String, Object>> orderListData(
        String orderNo, String passengerPhone, String employPhone, String companyName,
        String startTime, String endTime, String allorderType, String allstatus, Boolean treatment,
        String startFinishTime, String endFinishTime, Integer page, Integer rows)
        throws ParseException {
        //分公司查询本公司数据
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.QUERY_ORDERLIST)
            .append(".json?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (page != null) {
            kv.put("page", String.valueOf(page + 1));
            builder.append("&page={page}");
        }
        if (rows != null) {
            kv.put("rows", String.valueOf(rows));
            builder.append("&rows={rows}");
        }
        if (treatment != null) {
            kv.put("treatment", treatment.toString());
            builder.append("&treatment={treatment}");
        }
        kv.put("orderby", "status asc,finishTime desc,startTime asc");
        builder.append("&orderby={orderby}");
        if (StringUtils.isNotBlank(orderNo)) {
            kv.put("orderNo", orderNo);
            builder.append("&orderNo={orderNo}");
        }

        if (StringUtils.isNotBlank(passengerPhone)) {
            kv.put("passengerName", passengerPhone);
            builder.append("&passengerName={passengerName}");
        }
        if (StringUtils.isNotBlank(employPhone)) {
            kv.put("employName", employPhone);
            builder.append("&employName={employName}");
        }
        if (StringUtils.isNotBlank(companyName)) {
            kv.put("companyName", companyName);
            builder.append("&companyName={companyName}");
        }
        if (StringUtils.isNotBlank(startTime)) {
            Date start = DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm");
            kv.put("startTime", String.valueOf(start.getTime()));
            builder.append("&startTime={startTime}");
        }
        if (StringUtils.isNotBlank(endTime)) {
            Date end = DateUtils.parseDate(endTime, "yyyy-MM-dd HH:mm");
            kv.put("endTime", String.valueOf(end.getTime()));
            builder.append("&endTime={endTime}");
        }
        if (StringUtils.isNotBlank(startFinishTime)) {
            Date start = DateUtils.parseDate(startFinishTime, "yyyy-MM-dd HH:mm");
            kv.put("startFinishTime", String.valueOf(start.getTime()));
            builder.append("&startFinishTime={startFinishTime}");
        }
        if (StringUtils.isNotBlank(endFinishTime)) {
            Date end = DateUtils.parseDate(endFinishTime, "yyyy-MM-dd HH:mm");
            kv.put("endFinishTime", String.valueOf(end.getTime()));
            builder.append("&endFinishTime={endFinishTime}");
        }
        if (StringUtils.isNotBlank(allorderType)) {
            kv.put("allorderType", allorderType);
            builder.append("&allorderType={allorderType}");
        }
        if (StringUtils.isNotBlank(allstatus)) {
            kv.put("allstatus", allstatus);
            builder.append("&allstatus={allstatus}");
        }

        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        List<Order> list = new ArrayList<Order>();
        long total = 0;
        List<Map<String, Object>> content = new ArrayList<Map<String, Object>>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                list = gson.fromJson(ja.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
            SimpleDateFormat format = new SimpleDateFormat("MM/dd HH:mm");
            for (Order order : list) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", order.getId());
                map.put("balanceMoney", order.getBalanceMoney());
                map.put("budgetPay", order.getBudgetPay());
                map.put("cancelCause",
                    order.getCancelCause() != null ? order.getCancelCause() : "-");
                map.put("truckTypeId", order.getTruckTypeId());
                map.put("truckTypeName", order.getTruckTypeName());
                map.put("truckTypeNumber", order.getTruckNumber());
                map.put("cangointotown",
                    (order.getTruckType() != null ? order.getTruckType().getCangointotown()
                        : false));
                map.put("channelName", order.getChannelName());
                map.put("companyId", order.getCompanyId());
                map.put("companyName", order.getCompanyName());
                map.put("created", format.format(order.getCreated()));
                map.put("employCompanyId", order.getEmployCompanyId());
                map.put("employId", order.getEmployId());
                map.put("employName", order.getEmployName() != null ? order.getEmployName() : "-");
                map.put("employPhone", UseAllDataUtil.useAllDataDriver(
                    order.getEmployPhone() != null ? order.getEmployPhone() : "-"));
                map.put("employProfit", order.getEmployProfit());
                map.put("mileage", order.getMileage());
                map.put("mileagePrice", order.getMileagePrice());
                map.put("runtime", order.getRunTime());
                map.put("realPay", order.getRealPay());
                map.put("preAndAfterPayType", order.getPreAndAfterPayType());
                map.put("budgetPay", order.getBudgetPay());
                map.put("orderNo", order.getOrderNo());
                map.put("passengerId", order.getPassengerId());
                map.put("passengerName", order.getPassengerName());
                map.put("passengerPhone", UseAllDataUtil.useAllData(order.getPassengerPhone()));
                map.put("review", order.getReview());
                map.put("serverTime", format.format(order.getStartTime()));
                map.put("startAddress", order.getStartAddress());
                map.put("startLng", order.getStartLng());
                map.put("startLat", order.getStartLat());
                map.put("endAddress", order.getDestination());
                map.put("endLat", order.getEndLat());
                map.put("endLng", order.getEndLng());
                map.put("startPrice", order.getStartPrice());
                map.put("waypoints", order.getWaypoints());
                map.put("status", order.getStatus());
                map.put("waitCost", order.getWaitCost());
                map.put("waitTime", order.getWaitTime());
                map.put("guoluMoney", order.getGuoluMoney());
                map.put("yuanchengMoney", order.getYuanchengMoney());
                map.put("otherMoney", order.getOtherMoney());
                map.put("flitting", order.getFlitting());
                map.put("receipt", order.getReceipt());
                map.put("receivedPay", order.getReceivedPay());
                map.put("payMount", order.getPayMount());
                map.put("memo", order.getMemo());
                map.put("justKilometres", order.getJustKilometres());
                map.put("justMoney", order.getJustMoney());
                String orderMemo = "";
                if (order.getOrderMemos() != null && order.getOrderMemos().size() != 0) {
                    List<OrderMemo> orderMemos = order.getOrderMemos();
                    for (int i = 0; i < orderMemos.size(); i++) {
                        orderMemo += ((i + 1) + ":");
                        orderMemo += (orderMemos.get(i).getMemo() + "\n");
                    }
                }
                map.put("orderMemo", orderMemo);
                String memoStr = "";
                if (order.getOrderMemos() != null && order.getOrderMemos().size() != 0) {
                    List<OrderMemo> orderMemos = order.getOrderMemos();
                    for (int i = 0; i < orderMemos.size(); i++) {
                        memoStr += (orderMemos.get(i).getMemo());
                    }
                }
                if (StringUtils.isNotBlank(memoStr)) {
                    memoStr += ";";
                }
                memoStr += order.getMemo();
                map.put("memoStr", memoStr);
                map.put("couponId", order.getCouponId());
                content.add(map);
            }
        }

        return new PageImpl<Map<String, Object>>(content, pageable, total);
    }

    @Override
    public List<Map<String, Object>> orderListDataExport(
        String orderNo, String passengerPhone, String employPhone, String companyName,
        String startTime, String endTime, String allorderType, String allstatus, Boolean treatment,
        String startFinishTime, String endFinishTime) throws ParseException {

        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.QUERY_ORDERLIST)
            .append(".json?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();

        if (treatment != null) {
            kv.put("treatment", treatment.toString());
            builder.append("&treatment={treatment}");
        }
        kv.put("orderby", "status asc,finishTime desc,startTime asc");
        builder.append("&orderby={orderby}");
        if (StringUtils.isNotBlank(orderNo)) {
            kv.put("orderNo", orderNo);
            builder.append("&orderNo={orderNo}");
        }

        if (StringUtils.isNotBlank(passengerPhone)) {
            kv.put("passengerName", passengerPhone);
            builder.append("&passengerName={passengerName}");
        }
        if (StringUtils.isNotBlank(employPhone)) {
            kv.put("employName", employPhone);
            builder.append("&employName={employName}");
        }
        if (StringUtils.isNotBlank(companyName)) {
            kv.put("companyName", companyName);
            builder.append("&companyName={companyName}");
        }
        if (StringUtils.isNotBlank(startTime)) {
            Date start = DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm");
            kv.put("startTime", String.valueOf(start.getTime()));
            builder.append("&startTime={startTime}");
        }
        if (StringUtils.isNotBlank(endTime)) {
            Date end = DateUtils.parseDate(endTime, "yyyy-MM-dd HH:mm");
            kv.put("endTime", String.valueOf(end.getTime()));
            builder.append("&endTime={endTime}");
        }
        if (StringUtils.isNotBlank(startFinishTime)) {
            Date start = DateUtils.parseDate(startFinishTime, "yyyy-MM-dd HH:mm");
            kv.put("startFinishTime", String.valueOf(start.getTime()));
            builder.append("&startFinishTime={startFinishTime}");
        }
        if (StringUtils.isNotBlank(endFinishTime)) {
            Date end = DateUtils.parseDate(endFinishTime, "yyyy-MM-dd HH:mm");
            kv.put("endFinishTime", String.valueOf(end.getTime()));
            builder.append("&endFinishTime={endFinishTime}");
        }
        if (StringUtils.isNotBlank(allorderType)) {
            kv.put("allorderType", allorderType);
            builder.append("&allorderType={allorderType}");
        }
        if (StringUtils.isNotBlank(allstatus)) {
            kv.put("allstatus", allstatus);
            builder.append("&allstatus={allstatus}");
        }

        builder.append("&page={page}");
        builder.append("&rows={rows}");

        Integer rows = 100;
        Integer currentRows = 0;
        Integer page = 0;

        kv.put("page", String.valueOf(page + 1));
        kv.put("rows", String.valueOf(rows));

        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        List<Map<String, Object>> content = new ArrayList<Map<String, Object>>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {

                Long total = 0l;
                List<Order> list = new ArrayList<Order>();
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Order>>() {
                }.getType());

                if (total > 0) {
                    currentRows += rows;
                    page++;
                    while (currentRows < total) {
                        kv.put("page", String.valueOf(page + 1));
                        kv.put("rows", String.valueOf(rows));
                        String result2 = freightApi.get(builder.toString(), kv, settingUtils.get());
                        if (null != result2) {
                            JSONObject jo2 = new JSONObject(result2);
                            Integer code2 = jo2.getInt("code");
                            if (code2 == 0) {
                                Long total2 = 0l;
                                List<Order> list2 = new ArrayList<Order>();
                                JSONObject data2 = jo2.getJSONObject("data");
                                total2 = data.getLong("total");
                                JSONArray ja2 = data2.getJSONArray("rows");
                                list2 = gson.fromJson(ja2.toString(), new TypeToken<List<Order>>() {
                                }.getType());
                                if (total2 > 0) {
                                    list.addAll(list2);
                                }
                            }
                        }
                        currentRows += rows;
                        page++;
                    }

                    SimpleDateFormat format = new SimpleDateFormat("MM/dd HH:mm");
                    for (Order order : list) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("id", order.getId());
                        map.put("balanceMoney", order.getBalanceMoney());
                        map.put("budgetPay", order.getBudgetPay());
                        map.put("cancelCause",
                            order.getCancelCause() != null ? order.getCancelCause() : "-");
                        map.put("truckTypeId", order.getTruckTypeId());
                        map.put("truckTypeName", order.getTruckTypeName());
                        map.put("truckTypeNumber", order.getTruckNumber());
                        map.put("cangointotown",
                            (order.getTruckType() != null ? order.getTruckType().getCangointotown()
                                : false));
                        map.put("channelName", order.getChannelName());
                        map.put("companyId", order.getCompanyId());
                        map.put("companyName", order.getCompanyName());
                        map.put("created", format.format(order.getCreated()));
                        map.put("employCompanyId", order.getEmployCompanyId());
                        map.put("employId", order.getEmployId());
                        map.put("employName",
                            order.getEmployName() != null ? order.getEmployName() : "-");
                        map.put("employPhone", UseAllDataUtil.useAllDataDriver(
                            order.getEmployPhone() != null ? order.getEmployPhone() : "-"));
                        map.put("employProfit", order.getEmployProfit());
                        map.put("mileage", order.getMileage());
                        map.put("mileagePrice", order.getMileagePrice());
                        map.put("runtime", order.getRunTime());
                        map.put("realPay", order.getRealPay());
                        map.put("preAndAfterPayType", order.getPreAndAfterPayType());
                        map.put("budgetPay", order.getBudgetPay());
                        map.put("orderNo", order.getOrderNo());
                        map.put("passengerId", order.getPassengerId());
                        map.put("passengerName", order.getPassengerName());
                        map.put("passengerPhone",
                            UseAllDataUtil.useAllData(order.getPassengerPhone()));
                        map.put("review", order.getReview());
                        map.put("serverTime", format.format(order.getStartTime()));
                        map.put("startAddress", order.getStartAddress());
                        map.put("startLng", order.getStartLng());
                        map.put("startLat", order.getStartLat());
                        map.put("endAddress", order.getDestination());
                        map.put("endLat", order.getEndLat());
                        map.put("endLng", order.getEndLng());
                        map.put("startPrice", order.getStartPrice());
                        map.put("waypoints", order.getWaypoints());
                        map.put("status", order.getStatus());
                        map.put("waitCost", order.getWaitCost());
                        map.put("waitTime", order.getWaitTime());
                        map.put("guoluMoney", order.getGuoluMoney());
                        map.put("yuanchengMoney", order.getYuanchengMoney());
                        map.put("otherMoney", order.getOtherMoney());
                        map.put("flitting", order.getFlitting());
                        map.put("receipt", order.getReceipt());
                        map.put("receivedPay", order.getReceivedPay());
                        map.put("payMount", order.getPayMount());
                        map.put("memo", order.getMemo());
                        map.put("justKilometres", order.getJustKilometres());
                        map.put("justMoney", order.getJustMoney());

                        String orderMemo = "";
                        if (order.getOrderMemos() != null && order.getOrderMemos().size() != 0) {
                            List<OrderMemo> orderMemos = order.getOrderMemos();
                            for (int i = 0; i < orderMemos.size(); i++) {
                                orderMemo += ((i + 1) + ":");
                                orderMemo += (orderMemos.get(i).getMemo() + "\n");
                            }
                        }
                        map.put("orderMemo", orderMemo);
                        String memoStr = "";
                        if (order.getOrderMemos() != null && order.getOrderMemos().size() != 0) {
                            List<OrderMemo> orderMemos = order.getOrderMemos();
                            for (int i = 0; i < orderMemos.size(); i++) {
                                memoStr += (orderMemos.get(i).getMemo());
                            }
                        }
                        if (StringUtils.isNotBlank(memoStr)) {
                            memoStr += ";";
                        }
                        memoStr += order.getMemo();
                        map.put("memoStr", memoStr);
                        map.put("couponId", order.getCouponId());
                        content.add(map);
                    }

                }
            }

        }

        return content;
    }


    @Override
    public Result<Order> callback(Long id, Driver driver, String cause) {
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();
        String operator = principal.getUsername();
        Result<Order> result = new Result<Order>();
        result.setSuccess(false);
        StringBuilder sb = new StringBuilder();
        sb.append(freightApi.getFreightBaseURL()).append(FreightApi.CALLBACK)
            .append("?appKey={appKey}");
        sb.append("&orderId={orderId}");
        sb.append("&action={action}");
        sb.append("&operator={operator}");
        sb.append("&cause={cause}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("orderId", String.valueOf(id));
        kv.put("action", "callback");
        kv.put("cause", cause);
        kv.put("operator", operator);
        String resultStr = freightApi.put(sb.toString(), kv, settingUtils.get());
        if (StringUtils.isBlank(resultStr)) {
            result.setSuccess(true);
            result.setMessage("收回订单成功");
            if (null != driver) {
                if (driver.getStatus() != Driver.DRIVER_OFFLINE) {
                    driverService
                        .updateStatusAndJobStatus(Driver.DRIVER_ONLINE, null, driver.getId());
                }
            }
        } else {
            result.setSuccess(false);
            result.setMessage("收回订单失败");
        }

        return result;
    }

    @Override
    public Result<Order> autoCallback(Order order, Driver driver) {

        Result<Order> result = new Result<Order>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();
        sb.append(freightApi.getFreightBaseURL()).append(FreightApi.CALLBACK)
            .append("?appKey={appKey}");
        sb.append("&orderId={orderId}");
        sb.append("&action={action}");
        sb.append("&operator={operator}");
        sb.append("&cause={cause}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("orderId", String.valueOf(order.getId()));
        kv.put("action", "callback");
        kv.put("cause", "时间逾期，系统自动收回了该订单");
        kv.put("operator", "系统");

        String resultStr = freightApi.put(sb.toString(), kv, settingUtils.get());
        if (StringUtils.isBlank(resultStr)) {
            result.setSuccess(true);
            result.setMessage("收回订单成功");
            if (null != driver) {
                if (driver.getStatus() != Driver.DRIVER_OFFLINE) {
                    driverService
                        .updateStatusAndJobStatus(Driver.DRIVER_ONLINE, null, driver.getId());
                }
            }
        } else {
            result.setSuccess(false);
            result.setMessage("收回订单失败");
        }

        return result;
    }


    @Override
    public Page<TruckType> truckTypeDate(Long companyId, String companyName) {
        List<TruckType> list = new ArrayList<TruckType>();
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.QUERY_TRUCKTYPE_COMPANY)
            .append("?appKey={appKey}&page={page}&rows={rows}");
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));
        if (StringUtils.isNotBlank(companyName)) {
            kv.put("companyName", companyName);
            builder.append("&companyName={companyName}");
        }
        if (companyId != null) {
            kv.put("companyId", companyId + "");
            builder.append("&companyId={companyId}");
        }
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        Long total = 0L;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                list = gson.fromJson(ja.toString(), new TypeToken<List<TruckType>>() {
                }.getType());
                if (list != null && list.size() != 0) {
                    for (TruckType truckType : list) {
                        Area area = areaMapper.selectByPrimaryKey(truckType.getAreaId());
                        if (area != null) {
                            truckType.setAreaName(area.getName());
                        }
                    }
                }
            }
        }
        return new PageImpl<TruckType>(list, pageable, total);
    }

    @Override
    public Result<Order> paidan(Driver driver, Order order) {
        Result<Order> result = new Result<Order>();
        result.setSuccess(false);

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();
        String operator = principal.getUsername();

        StringBuilder sb = new StringBuilder();
        sb.append(freightApi.getFreightBaseURL()).append(
            FreightApi.PAIDAN_ORDER);//.append("?action={action}&orderId={orderId}&operator={operator}&appKey={appKey}");
        //Map<String,String> kv = new HashMap<String,String>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("operator", operator);
        kv.add("action", "paidan");

        kv.add("orderId", String.valueOf(order.getId()));

        //  sb.append("&employId={employId}&employName={employName}&employPhone={employPhone}&employNo={employNo}&employPhoto={employPhoto}&employScore={employScore}&employCompanyId={employCompanyId}");
        kv.add("employId", String.valueOf(driver.getId()));
        kv.add("employName", driver.getName());
        kv.add("employPhone", driver.getPhone());
        kv.add("employNo", driver.getUsername());
        Setting setting = settingUtils.get();
        kv.add("employPhoto", setting.getWebUrl() + "/upload/driver/" + driver.getPhoto());
        kv.add("employScore", String.valueOf(driver.getStarLevel()));
        kv.add("employCompanyId", String.valueOf(driver.getCompanyId()));

        String resultStr = freightApi.putMultiValueMap(sb.toString(), kv, settingUtils.get());

        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            String message = jo.getString("message");
            result.setMessage(message);
        } else {
            driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_APPLY_ORDER,
                Driver.DRIVER_JOBSTATUS_FREIGHT, driver.getId());
            result.setSuccess(true);

            //自动收回
            if (setting.getRevokeTime() != 0) {
                try {
                    //专车订单自动收回定时器
                    Timer timer = new Timer();
                    OrderRevokeTimerTask orderRevokeTimerTask = new OrderRevokeTimerTask(
                        order.getId(), "freight", applicationEventMulticaster);
                    Integer howLong = setting.getRevokeTime();
                    timer.schedule(orderRevokeTimerTask, howLong * 1000);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }
        return result;
    }


    @Override
    public Long countActivedOrdersByDriver(Long driverId) {

        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.QUERY_EXEORDER)
            .append("?employId={employId}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("employId", String.valueOf(driverId));
        Long total = 0L;
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                List<Order> list = gson.fromJson(data.toString(), new TypeToken<List<Order>>() {
                }.getType());
                total = (long) list.size();

            }
        }
        return total;
    }

    @Override
    public Page<Truck> queryByParamsCars(String companyName, String truckType,
        String carNumber, String driverName, String status) {
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.QUERY_PARAMS_TRUCKS)
            .append("?appKey={appKey}&page={page}&rows={rows}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));
        if (StringUtils.isNotBlank(companyName)) {
            kv.put("companyName", companyName);
            builder.append("&companyName={companyName}");
        }
        if (StringUtils.isNotBlank(truckType)) {
            kv.put("truckTypeName", truckType);
            builder.append("&truckTypeName={truckTypeName}");
        }
        if (StringUtils.isNotBlank(carNumber)) {
            kv.put("carNumber", carNumber);
            builder.append("&carNumber={carNumber}");
        }
        if (StringUtils.isNotBlank(driverName)) {
            kv.put("driverName", driverName);
            builder.append("&driverName={driverName}");
        }
        if (StringUtils.isNotBlank(status)) {
            kv.put("status", status);
            builder.append("&status={status}");
        }
        List<Truck> list = new ArrayList<Truck>();
        long total = 0;
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                list = gson.fromJson(ja.toString(), new TypeToken<List<Truck>>() {
                }.getType());
            }
        }
        return new PageImpl<Truck>(list, pageable, total);
    }

    @Override
    public Truck createCar(Long companyId, String companyName, String carNumber,
        Long truckTypeId, String name, String truckTypeName, Long employId, String employName) {
        Truck truck = null;
        Map<String, String> kv = new HashMap<String, String>();
        StringBuilder sb = new StringBuilder();
        sb.append(freightApi.getFreightBaseURL()).append(FreightApi.CREATE_TRUCK)
            .append("?appKey={appKey}");
        if (companyId != null) {
            sb.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        if (StringUtils.isNotBlank(companyName)) {
            sb.append("&companyName={companyName}");
            kv.put("companyName", String.valueOf(companyName));
        }
        if (StringUtils.isNotBlank(name)) {
            sb.append("&name={name}");
            kv.put("name", name);
        }
        if (StringUtils.isNotBlank(carNumber)) {
            sb.append("&carNumber={carNumber}");
            kv.put("carNumber", carNumber);
        }
        if (StringUtils.isNotBlank(truckTypeName)) {
            sb.append("&truckTypeName={truckTypeName}");
            kv.put("truckTypeName", truckTypeName);
        }
        if (truckTypeId != null) {
            sb.append("&truckTypeId={truckTypeId}");
            kv.put("truckTypeId", String.valueOf(truckTypeId));
        }

        if (employId != null && employId != 0) {
            kv.put("driverId", String.valueOf(employId));
            sb.append("&driverId={driverId}");
        }
        if (StringUtils.isNotBlank(employName)) {
            sb.append("&driverName={driverName}");
            kv.put("driverName", employName);
        }
        String result = freightApi.post(sb.toString(), kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            JSONObject data = jo.getJSONObject("data");
            Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
            ;
            truck = gson.fromJson(data.toString(), Truck.class);
            if (truck != null && employId != null) {
                Driver driver = driverMapper.selectByPrimaryKey(employId);
                if (driver != null && driver.getTruckId() != null) {
                    driver.setTruckId(truck.getId());
                    driverMapper.updateByPrimaryKey(driver);
                }
            }
        }

        return truck;
    }

    @Override
    public Truck findTruck(Long truckId) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.QUERY_TRUCK)
            .append("?truckId={truckId}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        Truck truck = null;
        kv.put("truckId", String.valueOf(truckId));
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                if (data != null) {
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    ;
                    truck = gson.fromJson(data.toString(), Truck.class);
                }
            }
        }
        return truck;
    }

    @Override
    public Map<String, Object> updateTruck(Long id, Long companyId,
        String companyName, String name, String carNumber,
        Long truckTypeId, String truckTypeName, Integer status,
        Long employId, String employName) {
        Map<String, Object> map = new HashMap<String, Object>();
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.UPDATE_TRUCK)
            .append("?truckId={truckId}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("truckId", String.valueOf(id));
        if (companyId != null && companyId != 0) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        if (StringUtils.isNotBlank(companyName)) {
            builder.append("&companyName={companyName}");
            kv.put("companyName", companyName);
        }
        if (StringUtils.isNotBlank(name)) {
            builder.append("&name={name}");
            kv.put("name", name);
        }
        if (StringUtils.isNotBlank(carNumber)) {
            builder.append("&carNumber={carNumber}");
            kv.put("carNumber", carNumber);
        }
        if (truckTypeId != null && truckTypeId != 0) {
            builder.append("&truckTypeId={truckTypeId}");
            kv.put("truckTypeId", String.valueOf(truckTypeId));
        }
        if (status != null) {
            builder.append("&status={status}");
            kv.put("status", String.valueOf(status));
        }
        if (employId != null && employId != 0) {
            kv.put("driverId", String.valueOf(employId));
            builder.append("&driverId={driverId}");
        }
        kv.put("driverName", employName);
        builder.append("&driverName={driverName}");

        String result = null;
        try {
            if (employId != null) {
                Driver driver = driverMapper.selectByPrimaryKey(employId);

                if (id != driver.getTruckId()) {
                    Driver driver2 = driverMapper.selectByTruckId(id);
                    if (driver2 != null) {
                        driver2.setTruckId(null);
                        driverMapper.updateByPrimaryKey(driver2);
                    }
                    driver.setTruckId(id);
                    driverMapper.updateByPrimaryKey(driver);
                } else if (driver.getTruckId() == null) {
                    Driver driver2 = driverMapper.selectByTruckId(id);
                    if (driver2 != null) {
                        driver2.setTruckId(null);
                        driverMapper.updateByPrimaryKey(driver2);
                    }
                    driver.setTruckId(id);
                    driverMapper.updateByPrimaryKey(driver);
                }

            }
            if (StringUtils.isBlank(employName)) {
                Driver driver = driverMapper.selectByTruckId(id);
                if (driver != null) {
                    driver.setTruckId(null);
                    driverMapper.updateByPrimaryKey(driver);
                }
            }

            result = freightApi.put(builder.toString(), kv, settingUtils.get());
        } catch (HttpClientErrorException e) {
            result = e.getResponseBodyAsString();
        } catch (HttpServerErrorException e) {
            result = e.getResponseBodyAsString();
        }

        if (StringUtils.isBlank(result)) {
            map.put("success", true);
            map.put("message", "修改成功！");
        } else {
            map.put("success", false);
            map.put("message", result);
        }
        return map;
    }

    @Override
    public List<Truck> findTruckByNumber(String carNumber) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.QUERY_TRUCK_CARNUMBER)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("carNumber", carNumber);
        builder.append("&carNumber={carNumber}");

        List<Truck> list = new ArrayList<Truck>();
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                list = gson.fromJson(data.toString(), new TypeToken<List<Truck>>() {
                }.getType());
            }
        }
        return list;
    }

    @Override
    public int deleteTruck(Long id) {
        int i = 0;
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.DELETE_TRUCK)
            .append("?truckId={truckId}&appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("truckId", String.valueOf(id));
        String result = freightApi.delete(builder.toString(), kv, settingUtils.get());
        if (StringUtils.isBlank(result)) {
            i = 1;
        }
        return i;
    }

    @Override
    public ChartYear dataForYear(Integer year, Long companyId) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.ORDERSTATISTICS)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (year != null) {
            builder.append("&year={year}");
            kv.put("year", String.valueOf(year));
        }
        if (companyId != null) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        ChartYear chartYear = null;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");

                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                chartYear = gson.fromJson(data.toString(), ChartYear.class);
            }
        }

        return chartYear;
    }

    @Override
    public ChartMonth freightDataForMonth(Integer year, Integer month,
        Long companyId) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.ORDERSTATISTICSMONTH)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (year != null) {
            builder.append("&year={year}");
            kv.put("year", String.valueOf(year));
        }
        if (month != null) {
            builder.append("&month={month}");
            kv.put("month", String.valueOf(month));
        }
        if (companyId != null) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        ChartMonth chartMonth = null;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");

                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                chartMonth = gson.fromJson(data.toString(), ChartMonth.class);
            }
        }
        return chartMonth;
    }

    @Override
    public ChartDay freightDataForDay(Integer year, Integer month, Integer day,
        Long companyId) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.ORDERSTATISTICSDAY)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (year != null) {
            builder.append("&year={year}");
            kv.put("year", String.valueOf(year));
        }
        if (month != null) {
            builder.append("&month={month}");
            kv.put("month", String.valueOf(month));
        }
        if (day != null) {
            builder.append("&day={day}");
            kv.put("day", String.valueOf(day));
        }
        if (companyId != null) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        ChartDay chartDay = null;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");

                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                chartDay = gson.fromJson(data.toString(), ChartDay.class);
            }
        }

        return chartDay;
    }

    @Override
    public PageVo<DriverOrderVo> freightIntroduce(Long companyId, Date start,
        Date end) {
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        StringBuilder sb = new StringBuilder();
        sb.append(freightApi.getFreightBaseURL()).append(FreightApi.DRIVERACHIEVEMENT)
            .append("?appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();
        if (principal.isCompanyType()) {
            if (null != companyId) {
                kv.put("companyId", String.valueOf(companyId));
                sb.append("&companyId={companyId}");
            }
        } else {
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            sb.append("&companyId={companyId}");
        }
        if (start != null) {
            kv.put("startDate", String.valueOf(start.getTime()));
            sb.append("&startDate={startDate}");
        }
        if (end != null) {
            kv.put("endDate", String.valueOf(end.getTime()));
            sb.append("&endDate={endDate}");
        }

        String result = freightApi.get(sb.toString(), kv, settingUtils.get());

        PageVo<DriverOrderVo> list = new PageVo<DriverOrderVo>();

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                list = gson.fromJson(data.toString(), new TypeToken<PageVo<DriverOrderVo>>() {
                }.getType());
            }
        }
        return list;
    }

    @Override
    public List<TableOrderMonthVo> tableOrderMonth(Integer year, Long companyId) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.ORDERSTATISTICS)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (year != null) {
            builder.append("&year={year}");
            kv.put("year", String.valueOf(year));
        }
        if (companyId != null) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        ChartYear chartYear = null;
        List<TableOrderMonthVo> lists = new ArrayList<TableOrderMonthVo>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");

                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                chartYear = gson.fromJson(data.toString(), ChartYear.class);
                for (ChartMonth month : chartYear.getMonths()) {
                    TableOrderMonthVo tomv = new TableOrderMonthVo();
                    tomv.setCancelAmount(month.getTotalCancelNum());
                    tomv.setFinishedAmount(month.getTotalSuccessNum());
                    tomv.setMoney(month.getTotalPrice());
                    tomv.setTime(month.getMonth());
                    lists.add(tomv);
                }
            }

        }
        return lists;
    }

    @Override
    public PageVo<OrderFromSourceVo> orderFromSource(Date start, Date end,
        Long companyId) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.ORDERTYPESTATISTICS)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (start != null) {
            builder.append("&startDate={startDate}");
            kv.put("startDate", start.getTime() + "");
        }
        if (end != null) {
            builder.append("&endDate={endDate}");
            kv.put("endDate", end.getTime() + "");
        }

        if (companyId != null) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        PageVo<OrderFromSourceVo> orderFromSourceVos = null;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                orderFromSourceVos = gson
                    .fromJson(data.toString(), new TypeToken<PageVo<OrderFromSourceVo>>() {
                    }.getType());
            }
        }

        return orderFromSourceVos;
    }

    @Override
    public List<Order> findMonthOrder(Integer year, Integer month) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.FREIGHTHEATMAP)
            .append(".json?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (month != null) {
            builder.append("&month={month}");
            kv.put("month", String.valueOf(month));
        }
        if (year != null) {
            builder.append("&year={year}");
            kv.put("year", String.valueOf(year));
        }
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());

        List<Order> list = new ArrayList<Order>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Object data = jo.get("data");

                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                list = gson.fromJson(data.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
        }
        return list;
    }

    public PageVo<CompanyOrderVo> companyOrder(Date start, Date end) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.COMPANYORDERSTATISTICS)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (start != null) {
            builder.append("&startDate={startDate}");
            kv.put("startDate", start.getTime() + "");
        }
        if (end != null) {
            builder.append("&endDate={endDate}");
            kv.put("endDate", end.getTime() + "");
        }

        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        PageVo<CompanyOrderVo> companyOrderVos = null;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");

                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                companyOrderVos = gson
                    .fromJson(data.toString(), new TypeToken<PageVo<CompanyOrderVo>>() {
                    }.getType());
            }
        }
        List<Company> companys = companyMapper.selectAll();
        List<CompanyOrderVo> vos = new ArrayList<CompanyOrderVo>();
        for (Company company : companys) {
            CompanyOrderVo vo = new CompanyOrderVo();
            vo.setCompanyName(company.getAbbreviation());
            for (CompanyOrderVo vo1 : companyOrderVos.getContent()) {
                if (vo1.getCompanyName().equals(vo.getCompanyName())) {
                    vo.setCancelNums(vo1.getCancelNums());
                    vo.setFinishNums(vo1.getFinishNums());
                    vo.setMoney(vo1.getMoney());
                    break;
                }
            }
            vos.add(vo);
        }
        companyOrderVos.setContent(vos);
        companyOrderVos.setTotalElements(vos.size());

        return companyOrderVos;
    }

    @Override
    public PageVo<MemberOrderVo> freightMemberOrder(Date start, Date end,
        Long companyId, Long gradeId, Integer type) {
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        StringBuilder sb2 = new StringBuilder();
        sb2.append(passengerApi.getPassengerBaseURL()).append(PassengerApi.QUERY_PASSENGER)
            .append("?appKey={appKey}&appId={appId}&sign={sign}&page={page}&rows={rows}");

        Map<String, String> kv2 = new HashMap<String, String>();
        kv2.put("page", String.valueOf(Pager.getPage() + 1));
        kv2.put("rows", String.valueOf(Pager.getLimit()));
        if (principal.isCompanyType()) {
            if (null != companyId) {
                kv2.put("companyId", String.valueOf(companyId));
                sb2.append("&companyId={companyId}");
            }
        } else {
            kv2.put("companyId", String.valueOf(principal.getCompanyId()));
            sb2.append("&companyId={companyId}");
        }

        if (null != gradeId) {
            kv2.put("gradeId", String.valueOf(gradeId));
            sb2.append("&gradeId={gradeId}");
        }
        if (null != type) {
            kv2.put("type", String.valueOf(type));
            sb2.append("&type={type}");
        }

        String result2 = passengerApi.get(sb2.toString(), kv2, settingUtils.get());

        List<Passenger> content2 = new ArrayList<Passenger>();
        if (null != result2) {
            JSONObject jo = new JSONObject(result2);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                content2 = gson.fromJson(ja.toString(), new TypeToken<List<Passenger>>() {
                }.getType());
            }
        }
        StringBuilder sb1 = new StringBuilder();
        sb1.append(passengerApi.getPassengerBaseURL()).append(PassengerApi.QUERY_PASSENGER)
            .append("?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv1 = new HashMap<String, String>();

        if (principal.isCompanyType()) {
            if (null != companyId) {
                kv1.put("companyId", String.valueOf(companyId));
                sb1.append("&companyId={companyId}");
            }
        } else {
            kv1.put("companyId", String.valueOf(principal.getCompanyId()));
            sb1.append("&companyId={companyId}");
        }

        if (null != gradeId) {
            kv1.put("gradeId", String.valueOf(gradeId));
            sb1.append("&gradeId={gradeId}");
        }
        if (null != type) {
            kv1.put("type", String.valueOf(type));
            sb1.append("&type={type}");
        }

        String result1 = passengerApi.get(sb1.toString(), kv1, settingUtils.get());

        List<Passenger> findAll = new ArrayList<Passenger>();

        if (null != result1) {
            JSONObject jo = new JSONObject(result1);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                findAll = gson.fromJson(ja.toString(), new TypeToken<List<Passenger>>() {
                }.getType());
            }
        }
        StringBuilder sb = new StringBuilder();
        sb.append(freightApi.getFreightBaseURL()).append(FreightApi.FREIGHTMEMBERORDER)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (principal.isCompanyType()) {
            if (null != companyId) {
                kv.put("companyId", String.valueOf(companyId));
                sb.append("&companyId={companyId}");
            }
        } else {
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            sb.append("&companyId={companyId}");
        }
        if (null != start) {
            kv.put("startTime", String.valueOf(start.getTime()));
            sb.append("&startTime={startTime}");
        }
        if (null != end) {
            kv.put("endTime", String.valueOf(end.getTime()));
            sb.append("&endTime={endTime}");
        }

        String result = freightApi.get(sb.toString(), kv, settingUtils.get());
        PageVo<MemberOrderVo> content = new PageVo<MemberOrderVo>();

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");

                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                content = gson.fromJson(data.toString(), new TypeToken<PageVo<MemberOrderVo>>() {
                }.getType());
            }
        }
        PageVo<MemberOrderVo> vopage = new PageVo<MemberOrderVo>();
        List<MemberOrderVo> volist = new ArrayList<MemberOrderVo>();
        MemberOrderVo count = new MemberOrderVo();
        count.setName("总计");
        count.setPhone("");
        count.setCompanyName(" ");
        count.setMoney(BigDecimal.ZERO);
        for (Passenger passenger : findAll) {
            for (MemberOrderVo memberOrderVo : content.getContent()) {
                if (passenger.getId().equals(memberOrderVo.getId())) {
                    count.setFinishNums(count.getFinishNums() + memberOrderVo.getFinishNums());
                    count.setMoney(count.getMoney().add(memberOrderVo.getMoney()));
                }
            }
        }

        MemberOrderVo count2 = new MemberOrderVo();
        count2.setName("当前页总计");
        count2.setPhone("");
        count2.setCompanyName(" ");
        count2.setMoney(BigDecimal.ZERO);

        for (Passenger passenger : content2) {
            MemberOrderVo mv = new MemberOrderVo();
            mv.setId(passenger.getId());
            mv.setName(passenger.getName());
            mv.setPhone(passenger.getPhone());
            mv.setCompanyName(passenger.getCompanyName());
            for (MemberOrderVo memberOrderVo : content.getContent()) {
                if (passenger.getId().equals(memberOrderVo.getId())) {
                    mv.setFinishNums(memberOrderVo.getFinishNums());
                    mv.setMoney(memberOrderVo.getMoney());
                    break;

                }
            }
            volist.add(mv);
            count2.setFinishNums(count2.getFinishNums() + mv.getFinishNums());
            count2.setMoney(count2.getMoney().add(mv.getMoney()));
        }

        volist.add(count2);
        volist.add(count);
        vopage.setContent(volist);
        vopage.setTotalElements(findAll.size());
        return vopage;
    }

    @Override
    public void acceptInfoFee(Driver driver, Order order) {

        if (null != driver) {
            Setting setting = settingUtils.get();
            if (setting.getInfoFeeFreight() != 0) {
                if (null != setting.getInfoFeeType() && setting.getInfoFeeType()
                    .equals(InfoFeeType.acceptTask)) {
                    driver.setVirtual(
                        driver.getVirtual().subtract(new BigDecimal(setting.getInfoFeeFreight())));
                    driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                    //扣费记录
                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                    driverPaymentsRecord.setMoney(new BigDecimal(setting.getInfoFeeFreight()));
                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                    driverPaymentsRecord
                        .setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                    driverPaymentsRecord.setDriverId(driver.getId());
                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                    driverPaymentsRecord.setOrderId(order.getId());
                    driverPaymentsRecord.setOrderNumber(order.getOrderNo());
                    driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_FREIGHT);
                    driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                    driverPaymentsRecord
                        .setMemo("扣除公司所得保险费/信息费" + setting.getInfoFeeFreight() + "元。");
                    driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                    driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                    driverPaymentsRecord.setHappend(new Date());
                    driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                    //财务记录（保险费）
                    Company mainCompany = companyMapper.selectMainCompany();
                    DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                    FinancialRecord financialRecord = new FinancialRecord();
                    StringBuilder sb_f = new StringBuilder();
                    sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);//保险费
                    sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);//对象 服务人员
                    sb_f.append(format_f.format(new Date()));//年月日时间
                    sb_f.append(OrderNumberConfig
                        .padZero(financialRecordMapper.getRunningNumber() + 1));//流水号
                    financialRecord.setCode(sb_f.toString());
                    financialRecord.setCompanyId(mainCompany.getId());
                    financialRecord.setCompanyName(mainCompany.getAbbreviation());
                    financialRecord.setOrderCompanyId(mainCompany.getId());
                    financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                    financialRecord.setMemo(
                        "订单号【<a target='_blank' href='/freight/detail/" + order.getId() + "'>"
                            + order.getOrderNo() + "</a>】保险费/信息费");
                    financialRecord.setMoney(new BigDecimal(setting.getInfoFeeFreight()));
                    financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                    financialRecord.setWho(driver.getRealname());
                    financialRecord.setOrderId(order.getId());
                    financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                    financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_FREIGHT);
                    financialRecordMapper.insertRecord(financialRecord);
                }
            }

        }
    }

    @Override
    public List<Order> queryByEmployId(Long employId, String status) {
        List<Order> list = null;
        Map<String, String> kv = new HashMap<String, String>();

        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL());
        builder.append(FreightApi.FIND_MYWORK);
        builder.append("?appKey={appKey}&employId={employId}&status={status}");
        kv.put("employId", String.valueOf(employId));
        kv.put("status", status);
        String string = freightApi.get(builder.toString(), kv, settingUtils.get());
        JSONObject jsonObject = new JSONObject(string);
        int code = jsonObject.getInt("code");
        List<Order> newList = new ArrayList<Order>();
        if (code == 0) {
            JSONArray data = jsonObject.getJSONArray("data");
            Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
            ;
            list = gson.fromJson(data.toString(), new TypeToken<List<Order>>() {
            }.getType());
            for (Order order : list) {
                if (order.getTruckType() != null) {
                    Area area = areaMapper
                        .selectByPrimaryKeyWithCharge(order.getTruckType().getAreaId());
                    if (area != null) {
                        order.setArea(area);
                    }
                }
                newList.add(order);
            }
        }
        return newList;
    }

    public PageVo<DriverOrderDetailVo> driverOrderDetail(Long driverId, Date start, Date end) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.DRIVERORDERDETAILVO)
            .append(".json?appKey={appKey}&page={page}&rows={rows}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));
        if (driverId != null) {
            kv.put("driverId", driverId + "");
            builder.append("&driverId={driverId}");
        }
        if (start != null) {
            kv.put("startDate", start.getTime() + "");
            builder.append("&startDate={startDate}");
        }
        if (end != null) {
            kv.put("endDate", end.getTime() + "");
            builder.append("&endDate={endDate}");
        }
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        PageVo<DriverOrderDetailVo> page = new PageVo<DriverOrderDetailVo>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                page = gson.fromJson(data.toString(), new TypeToken<PageVo<DriverOrderDetailVo>>() {
                }.getType());
            }
        }

        return page;
    }

    @Override
    public List<Order> listNewOrders() {
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.QUERY_NEWORDERS)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();

        if (!principal.isCompanyType()) {
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            builder.append("&companyId={companyId}");
        }

        kv.put("page", "1");
        builder.append("&page={page}");

        kv.put("rows", "20");
        builder.append("&rows={rows}");

        List<Order> list = new ArrayList<Order>();
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                list = gson.fromJson(data.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
            for (Order order : list) {
                if (!CollectionUtils.isEmpty(order.getOrderMemos())) {
                    StringBuilder memoStr = new StringBuilder();
                    List<OrderMemo> orderMemos = order.getOrderMemos();
                    for (int i = 0; i < orderMemos.size(); i++) {
                        memoStr.append((i + 1) + ":");
                        memoStr.append(orderMemos.get(i).getMemo() + "\n");
                    }
                    order.setMemo(memoStr.toString());
                }
            }
        }

        return list;
    }

    @Override
    public List<Order> findActivedOrdersByDriver(Long driverId) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.QUERY_EXEORDER)
            .append("?employId={employId}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("employId", String.valueOf(driverId));
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        List<Order> list = null;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                list = gson.fromJson(data.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
        }
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Order> confirmTask(Order order, String jsonLocs) {
        Result<Order> result = new Result<Order>();
        StringBuilder builder = new StringBuilder(freightApi.getFreightBaseURL())
            .append(FreightApi.CONFIRM_TASK);
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("orderId", String.valueOf(order.getId()));
        kv.add("realPay", String.valueOf(order.getRealPay()));
        if (null != order.getGuoluMoney()) {
            kv.add("guoluMoney", String.valueOf(order.getGuoluMoney()));
        }
        if (null != order.getYuanchengMoney()) {
            kv.add("yuanchengMoney", String.valueOf(order.getYuanchengMoney()));
        }
        if (null != order.getOtherMoney()) {
            kv.add("otherMoney", String.valueOf(order.getOtherMoney()));
        }

        if (null != order.getPrePayTypeDetail()) {
            kv.add("prePayTypeDetail", String.valueOf(order.getPrePayTypeDetail()));
        }

        kv.add("startPrice", String.valueOf(order.getStartPrice()));

        kv.add("mileagePrice", String.valueOf(order.getMileagePrice()));

        kv.add("runTimePrice", String.valueOf(order.getRunTimePrice()));

        if (null != order.getWaitCost()) {
            kv.add("waitPrice", String.valueOf(order.getWaitCost()));
        }

        kv.add("mileage", String.valueOf(order.getMileage()));

        kv.add("midwayWait", String.valueOf(order.getWaitTime()));

        kv.add("runTime", String.valueOf(order.getRunTime()));
        if (StringUtils.isNotBlank(jsonLocs)) {
            kv.add("xml", jsonLocs);
        }

        if (StringUtils.isNotBlank(order.getMemo())) {
            kv.add("memo", order.getMemo());
        }
        if (null != order.getCouponMoney()) {
            kv.add("couponMoney", String.valueOf(order.getCouponMoney()));
        }
        if (null != order.getDiscount()) {
            kv.add("discount", String.valueOf(order.getDiscount()));
        }
        if (null != order.getJustKilometres()) {
            kv.add("justKilometres", String.valueOf(order.getJustKilometres()));
        }
        if (null != order.getJustMoney()) {
            kv.add("justMoney", String.valueOf(order.getJustMoney()));
        }

        String resultStr = freightApi.postMultiValueMap(builder.toString(), kv, settingUtils.get());

        logger.error("resultStr:{}", resultStr);
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                result.setSuccess(true);
            } else {
                String message = jo.getString("message");
                result.setSuccess(false);
                result.setMessage(message);
            }
        } else {
            result.setSuccess(false);
            result.setMessage("未知错误");
        }

        return result;

    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Order> confirmTaskV4(Order order, Driver driver) {

        Result<Order> result = new Result<Order>();

        driverMapper
            .updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_ONLINE, null, driver.getId());

        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Order> completeTaskNewV3(Order order, Passenger passenger, Driver driver,
        String completeType, String payType) {

        Result<Order> result = new Result<Order>();

        boolean ftSuccess = freightApi.addFinishTime(order.getId(), settingUtils.get()).isSuccess();

        if (order.getStatus().equals(Order.ORDER_STATUS_OK) || !ftSuccess) {
            result.setSuccess(false);
            result.setErrorcode(String.valueOf(ErrorConstantV4.ORDER_HAS_BEEN_FINISHED.getCode()));
            result.setMessage(ErrorConstantV4.ORDER_HAS_BEEN_FINISHED.getMessage());
            return result;
        }

        try {
            BigDecimal employProfit = BigDecimal.ZERO;
            BigDecimal companyProfit = BigDecimal.ZERO;

            //优惠券金额
            BigDecimal now_couponMoney = order.getCouponMoney();

            Double discount = order.getDiscount();

            //结算应支付的金额
            BigDecimal afterPayMoney = BigDecimal.ZERO;
            if (null != order.getPrePayTypeDetail()) {
                if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon)) {
                    afterPayMoney = new BigDecimal(order.getRealPay())
                        .subtract(order.getGuoluMoney()).subtract(now_couponMoney);
                    if (afterPayMoney.doubleValue() < 0) {
                        afterPayMoney = BigDecimal.ZERO;
                    }
                    afterPayMoney = afterPayMoney.add(order.getGuoluMoney());
                    afterPayMoney = afterPayMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
                }
            } else {
                afterPayMoney = new BigDecimal(order.getRealPay());
                afterPayMoney = afterPayMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
            }

            if ("clickPay".equals(completeType)) {//自己支付
                if ("helppay".equals(payType)) {//代付支付
                    order.setAfterPayTypeDetail(Order.PayTypeDetails.helppay);
                    order.setCashMoney(afterPayMoney);
                } else if ("sign".equals(payType)) {//签单支付
                    order.setAfterPayTypeDetail(Order.PayTypeDetails.sign);
                    order.setSignMoney(afterPayMoney);
                } else if ("balance".equals(payType)) {//余额支付
                    order.setAfterPayTypeDetail(Order.PayTypeDetails.balance);
                    order.setBalanceMoney(afterPayMoney);
                }
            } else if ("onlinePay".equals(completeType)) {//在线支付
                if ("alipay".equals(payType)) {//支付宝支付
                    order.setAfterPayTypeDetail(Order.PayTypeDetails.alipay);
                    order.setAlipayMoney(afterPayMoney);
                } else if ("weixin".equals(payType)) {
                    order.setAfterPayTypeDetail(Order.PayTypeDetails.weixin);
                    order.setWeixinMoney(afterPayMoney);
                } else if ("unionpay".equals(payType)) {
                    order.setAfterPayTypeDetail(Order.PayTypeDetails.unionpay);
                    order.setUnionpayMoney(afterPayMoney);
                }
            } else if ("clickComplete".equals(completeType)) {
                if (null != order.getPrePayTypeDetail()) {

                } else {
                    order.setAfterPayTypeDetail(PayTypeDetails.helppay);
                    order.setCashMoney(BigDecimal.ZERO);
                }
            }
            List<OrderStatus> orderStatuslist = order.getOrderStatusList();
            Date travelDate = null;
            if (!CollectionUtils.isEmpty(orderStatuslist)) {
                Collections.sort(orderStatuslist, new Comparator<OrderStatus>() {
                    public int compare(OrderStatus arg0, OrderStatus arg1) {
                        return arg1.getId().compareTo(arg0.getId());
                    }
                });
                if (!CollectionUtils.isEmpty(orderStatuslist)) {
                    for (OrderStatus orderStatus : orderStatuslist) {
                        if (orderStatus.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
                            travelDate = orderStatus.getCreated();
                            break;
                        }
                    }
                }
            }

            //客户相关
            if (null != passenger) {
                //实际价格小于或等于预付费
                if ("clickPay".equals(completeType)) {
                    if ("helppay".equals(payType)) {//如果是代付，服务人员收到现金，余额减钱
                        driver.setVirtual(driver.getVirtual().subtract(afterPayMoney));
                        driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

                        DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                        driverPaymentsRecord.setMoney(afterPayMoney);
                        driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                        driverPaymentsRecord
                            .setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_HELPPAY);
                        driverPaymentsRecord.setDriverId(driver.getId());
                        driverPaymentsRecord.setDriverRealName(driver.getRealname());
                        driverPaymentsRecord.setDriverUserName(driver.getUsername());
                        driverPaymentsRecord.setDriverPhone(driver.getPhone());
                        driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                        driverPaymentsRecord.setOrderId(order.getId());
                        driverPaymentsRecord.setOrderNumber(order.getOrderNo());
                        driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_FREIGHT);
                        driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                        driverPaymentsRecord
                            .setMemo("为客户【" + passenger.getName() + "】代付" + afterPayMoney + "元。");
                        driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                        driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                        driverPaymentsRecord.setHappend(new Date());
                        driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);
                    }
                }

                //结算记录
                if ("clickPay".equals(completeType) || "onlinePay".equals(completeType)) {
                    String memo = "";
                    PassengerAccount.PayType ptype = null;
                    if (order.getAfterPayTypeDetail().equals(PayTypeDetails.helppay)) {
                        memo += "结算使用代付" + afterPayMoney.toString() + "元。";
                        ptype = PassengerAccount.PayType.PAYTYPE_CASH;
                    }
                    if (order.getAfterPayTypeDetail().equals(PayTypeDetails.sign)) {
                        memo += "结算使用签单支付" + afterPayMoney.toString() + "元。";
                        ptype = PassengerAccount.PayType.PAYTYPE_SIGN;
                    }
                    if (order.getAfterPayTypeDetail().equals(PayTypeDetails.balance)) {
                        memo += "结算使用余额支付" + afterPayMoney.toString() + "元。";
                        ptype = PassengerAccount.PayType.PAYTYPE_BALANCE;
                    }
                    if (order.getAfterPayTypeDetail().equals(PayTypeDetails.alipay)) {
                        memo += "结算使用支付宝支付" + afterPayMoney.toString() + "元。";
                        ptype = PassengerAccount.PayType.PAYTYPE_ALIPAY;
                    }
                    if (order.getAfterPayTypeDetail().equals(PayTypeDetails.unionpay)) {
                        memo += "结算使用银联支付" + afterPayMoney.toString() + "元。";
                        ptype = PassengerAccount.PayType.PAYTYPE_UNIONPAY;
                    }
                    if (order.getAfterPayTypeDetail().equals(PayTypeDetails.weixin)) {
                        memo += "结算使用微信支付" + afterPayMoney.toString() + "元。";
                        ptype = PassengerAccount.PayType.PAYTYPE_WEIXIN;
                    }

                    //是否更新余额
                    boolean updateBlance = false;
                    if (order.getAfterPayTypeDetail().equals(PayTypeDetails.sign) || order
                        .getAfterPayTypeDetail().equals(PayTypeDetails.balance)) {
                        updateBlance = true;
                    }

                    PassengerAccount passengerAccount = null;

                    if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                        Result<PassengerAccount> result_account = passengerApi
                            .createPassengerAccount(passenger, null, afterPayMoney.negate(), ptype,
                                PassengerAccount.OPERATING_SYS, memo, order.getId(),
                                order.getOrderNo(), PassengerAccount.ORDER_TYPE_FREIGHT, null,
                                updateBlance, true, settingUtils.get());
                        passengerAccount = result_account.getResult();
                    } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                        Enterprise enterprise = passengerApi
                            .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get())
                            .getResult();
                        if (null != enterprise) {
                            Result<PassengerAccount> result_account = passengerApi
                                .createEnterpriseAccount(enterprise, afterPayMoney.negate(), ptype,
                                    PassengerAccount.OPERATING_SYS, memo, order.getId(),
                                    order.getOrderNo(), PassengerAccount.ORDER_TYPE_FREIGHT, null,
                                    updateBlance, true, settingUtils.get());
                            passengerAccount = result_account.getResult();
                        }
                    }

                    if (updateBlance) {
                        //客户扣费短信
                        if (null != passengerAccount) {
                            if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                                MemberConsumedEvent consumedEvent = new MemberConsumedEvent(
                                    passengerAccount, null);
                                applicationEventMulticaster.multicastEvent(consumedEvent);
                            } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                                MemberConsumedEvent consumedEvent = new MemberConsumedEvent(
                                    passengerAccount, passenger.getPhone());
                                applicationEventMulticaster.multicastEvent(consumedEvent);
                            }
                        }
                    }
                }

                passenger.setMileage(passenger.getMileage() + order.getMileage());
                passenger.setDrivingNumberTimes(passenger.getDrivingNumberTimes() + 1);
                passengerApi.updatePersonal(passenger, settingUtils.get());

                if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                    Enterprise enterprise = passengerApi
                        .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get())
                        .getResult();
                    if (null != enterprise) {
                        enterprise.setDrivingNumberTimes(enterprise.getDrivingNumberTimes() + 1);
                        passengerApi.updateEnterpriseInfo(enterprise, settingUtils.get());
                    }
                }

                BigDecimal receiptMoney = new BigDecimal(order.getRealPay())
                    .subtract(order.getGuoluMoney()).subtract(order.getCouponMoney());
                if (receiptMoney.doubleValue() > 0) {
                    passengerApi
                        .createReceipt(passenger, receiptMoney.negate(), settingUtils.get());
                }
            }

            BigDecimal realCash = new BigDecimal(order.getRealPay())
                .subtract(order.getGuoluMoney());

            //优惠劵是否参与提成
            Setting setting = settingUtils.get();
            boolean couponTicheng = setting.isCouponTicheng();

            //是否使用了优惠劵
            if (order.getCouponId() != null) {
                if (!couponTicheng) {//不参与提成
                    realCash = realCash.subtract(order.getCouponMoney());
                    if (realCash.compareTo(BigDecimal.ZERO) == -1) {
                        realCash = BigDecimal.ZERO;
                    }
                }
            }

            //服务人员设为空闲
            boolean companyGetAll = false;//公司是否的全部

            DateFormat format = new SimpleDateFormat("yyyyMMdd");

            StringBuilder sbmemo = new StringBuilder();
            sbmemo.append(
                "订单【" + order.getOrderNo() + "】，客户【" + order.getPassengerName() + "(" + order
                    .getPassengerPhone() + ")】，");

            //预支付备注
            if (null != order.getPrePayTypeDetail()) {

                if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon)) {
                    if (null == discount) {
                        sbmemo.append("使用了" + order.getCouponMoney().toString() + "元优惠券。");
                    } else {
                        sbmemo.append("使用了" + discount.toString() + "折优惠券。");
                    }
                }

                if (couponTicheng) {
                    sbmemo.append("优惠劵参与提成计算。");
                } else {
                    sbmemo.append("优惠劵不参与提成计算。");
                }

            }

            //后支付备注
            if (null != order.getAfterPayTypeDetail()) {
                if (order.getAfterPayTypeDetail().equals(PayTypeDetails.helppay)) {
                    sbmemo.append("代付结算（" + afterPayMoney + "元）。");
                } else if (order.getAfterPayTypeDetail().equals(PayTypeDetails.sign)) {
                    sbmemo.append("签单支付结算（" + afterPayMoney + "元）。");
                } else if (order.getAfterPayTypeDetail().equals(PayTypeDetails.balance)) {
                    sbmemo.append("余额支付结算（" + afterPayMoney + "元）。");
                } else if (order.getAfterPayTypeDetail().equals(PayTypeDetails.alipay)) {
                    sbmemo.append("支付宝支付结算（" + afterPayMoney + "元）。");
                } else if (order.getAfterPayTypeDetail().equals(PayTypeDetails.weixin)) {
                    sbmemo.append("微信支付结算（" + afterPayMoney + "元）。");
                } else if (order.getAfterPayTypeDetail().equals(PayTypeDetails.unionpay)) {
                    sbmemo.append("银联支付结算（" + afterPayMoney + "元）。");
                }
            }

            if (null != driver) {
                driver.setTodayOrders(driver.getTodayOrders() + 1);
                driver.setMonthOrders(driver.getMonthOrders() + 1);
                driver.setDriveTimes(driver.getDriveTimes() + 1);
                driverMapper.updateWhenFinishOrderByKey(driver);

                //扣费 提成
                if (null != driver.getType() && Driver.DRIVER_TYPR_PARTTIME
                    .equals(driver.getType())) {

                    DriverChoseLevelFreight driverChoseLevelFreight = driverChoseLevelFreightMapper
                        .selectByDriverAndCompany(driver.getId(), order.getCompanyId());

                    if (null != driverChoseLevelFreight) {

                        DriverLevel driverLevel = null;

                        if (driverChoseLevelFreight.getDriverlevelId() == 0) {//始终使用本公司提成
                            DriverChoseLevelFreight driverChoseLevelFreight2 = driverChoseLevelFreightMapper
                                .selectByDriverAndCompany(driver.getId(), driver.getCompanyId());
                            if (null != driverChoseLevelFreight2) {
                                driverLevel = driverLevelMapper.selectByPrimaryKey(
                                    driverChoseLevelFreight2.getDriverlevelId());
                            }
                        } else {
                            driverLevel = driverLevelMapper
                                .selectByPrimaryKey(driverChoseLevelFreight.getDriverlevelId());
                        }

                        DriverLevelDetail detail = null;
                        DriverLevelMoneyTimeDetail moneyTimeDetail = null;

                        if (null != driverLevel) {
                            if (driverLevel.getType().equals(0)) {
                                driverLevel.setDriverLevelDetails(driverLevelDetailMapper
                                    .selectByDriverLevel(driverLevel.getId()));
                                if (driverLevel.getTimePoint().equals(TimePoint.serviceTime)) {
                                    detail = driverLevel.getDeatil(order.getStartTime());
                                } else if (driverLevel.getTimePoint()
                                    .equals(TimePoint.startDrive)) {
                                    detail = driverLevel.getDeatil(travelDate);
                                } else if (driverLevel.getTimePoint()
                                    .equals(TimePoint.finishTime)) {
                                    detail = driverLevel.getDeatil(new Date());
                                }
                            } else if (driverLevel.getType().equals(1)) {
                                driverLevel.setDriverLevelMoneyTimeDetails(
                                    driverLevelMoneyTimeDetailMapper
                                        .selectByDriverLevel(driverLevel.getId()));
                                if (driverLevel.getTimePoint().equals(TimePoint.serviceTime)) {
                                    moneyTimeDetail = driverLevel
                                        .getMoneyTimeDeatil(order.getStartTime());
                                } else if (driverLevel.getTimePoint()
                                    .equals(TimePoint.startDrive)) {
                                    moneyTimeDetail = driverLevel.getMoneyTimeDeatil(travelDate);
                                } else if (driverLevel.getTimePoint()
                                    .equals(TimePoint.finishTime)) {
                                    moneyTimeDetail = driverLevel.getMoneyTimeDeatil(new Date());
                                }
                            }
                        }

                        if (null != detail) {

                            BigDecimal money = BigDecimal.ZERO;
                            BigDecimal companyMoney = BigDecimal.ZERO;

                            if (detail.getDriverLevelType().equals(DriverLevelType.ticheng)) {
                                if (realCash.compareTo(detail.getMinCommission()) == -1) {
                                    money = realCash.subtract(detail.getLowCommission())
                                        .setScale(2, BigDecimal.ROUND_HALF_UP);
                                    companyMoney = detail.getLowCommission();
                                    if (money.doubleValue() < 0) {
                                        money = BigDecimal.ZERO;
                                        companyMoney = realCash;
                                    }
                                    sbmemo.append(
                                        "按照【低于" + detail.getMinCommission() + "元公司得" + detail
                                            .getLowCommission() + "元】方式，服务人员得" + money + "元。");
                                } else {
                                    money = realCash.multiply(
                                        new BigDecimal(100).subtract(detail.getCommission()))
                                        .divide(new BigDecimal(100));
                                    companyMoney = realCash.subtract(money);
                                    sbmemo.append("按照【" + detail.getCommission() + "%公司所得】提成方式。");
                                }
                            } else if (detail.getDriverLevelType().equals(DriverLevelType.guding)) {
                                if (realCash.compareTo(detail.getMinMoney()) == -1) {
                                    money = realCash.subtract(detail.getLowMoney())
                                        .setScale(2, BigDecimal.ROUND_HALF_UP);
                                    companyMoney = detail.getLowMoney();
                                    if (money.doubleValue() < 0) {
                                        money = BigDecimal.ZERO;
                                        companyMoney = realCash;
                                    }
                                    sbmemo.append("按照【低于" + detail.getMinMoney() + "元公司得" + detail
                                        .getLowMoney() + "元】方式，服务人员得" + money + "元。");
                                } else {

                                    sbmemo.append("按照【" + detail.getMoney() + "元公司所得】提成方式。");

                                    if (realCash.compareTo(detail.getMoney()) == -1) {
                                        money = BigDecimal.ZERO;
                                        companyMoney = realCash;
                                    } else {
                                        money = realCash.subtract(detail.getMoney());
                                        companyMoney = detail.getMoney();
                                    }

                                }
                            }

                            employProfit = money;
                            companyProfit = companyMoney;

                            driver.setVirtual(driver.getVirtual().add(money));
                            driverMapper
                                .updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

                            DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                            driverPaymentsRecord.setMoney(money);
                            driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                            driverPaymentsRecord
                                .setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_ORDER);
                            driverPaymentsRecord.setDriverId(driver.getId());
                            driverPaymentsRecord.setDriverRealName(driver.getRealname());
                            driverPaymentsRecord.setDriverUserName(driver.getUsername());
                            driverPaymentsRecord.setDriverPhone(driver.getPhone());
                            driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                            driverPaymentsRecord.setOrderId(order.getId());
                            driverPaymentsRecord.setOrderNumber(order.getOrderNo());
                            driverPaymentsRecord
                                .setOrderType(DriverPaymentsRecord.ORDER_TYPE_FREIGHT);
                            driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                            driverPaymentsRecord.setMemo(sbmemo.toString());
                            driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                            driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                            driverPaymentsRecord.setHappend(new Date());
                            driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                            //公司财务
                            String companyMemo =
                                "订单号【<a target='_blank' href='/freight/orderDetails/" + order
                                    .getId() + "'>" + order.getOrderNo() + "</a>】收入。";

                            Company company = companyMapper
                                .selectByPrimaryKey(driver.getCompanyId());
                            Company orderCompany = companyMapper
                                .selectByPrimaryKey(order.getCompanyId());

                            FinancialRecord financialRecord = new FinancialRecord();
                            StringBuilder sb = new StringBuilder();
                            sb.append(OrderNumberConfig.FINANCIAL_ORDER);//订单金额
                            sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);//对象 客户
                            sb.append(format.format(new Date()));//年月日时间
                            sb.append(OrderNumberConfig
                                .padZero(financialRecordMapper.getRunningNumber() + 1));//流水号
                            financialRecord.setCode(sb.toString());
                            financialRecord.setCompanyId(company.getId());
                            financialRecord.setCompanyName(company.getAbbreviation());
                            financialRecord.setOrderCompanyId(orderCompany.getId());
                            financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                            financialRecord.setMemo(companyMemo + driverPaymentsRecord.getMemo());
                            financialRecord.setMoney(companyMoney);
                            financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                            financialRecord.setWho(order.getPassengerName());
                            financialRecord.setOrderId(order.getId());
                            financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                            financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_FREIGHT);
                            financialRecordMapper.insertRecord(financialRecord);

                        } else if (null != moneyTimeDetail) {//复杂提成

                            BigDecimal money = BigDecimal.ZERO;
                            BigDecimal companyMoney = BigDecimal.ZERO;//公司所得金额

                            if (!CollectionUtils
                                .isEmpty(moneyTimeDetail.getDriverLevelMoneyDetails())) {

                                for (DriverLevelMoneyDetail dlmd : moneyTimeDetail
                                    .getDriverLevelMoneyDetails()) {
                                    if (realCash.doubleValue() >= dlmd.getFromMoney()
                                        .doubleValue()) {

                                        BigDecimal _money = BigDecimal.ZERO;
                                        if (realCash.doubleValue() >= dlmd.getToMoney()
                                            .doubleValue()) {
                                            _money = dlmd.getToMoney()
                                                .subtract(dlmd.getFromMoney());
                                        } else {
                                            _money = realCash.subtract(dlmd.getFromMoney());
                                        }

                                        if (dlmd.getDriverLevelMoneyType()
                                            .equals(DriverLevelMoneyType.guding)) {//固定
                                            BigDecimal tcMoney = dlmd.getMoney().multiply(
                                                new BigDecimal((int) (_money.doubleValue() / dlmd
                                                    .getMoneyUnit().doubleValue())));
                                            companyMoney = companyMoney.add(tcMoney);
                                        } else if (dlmd.getDriverLevelMoneyType()
                                            .equals(DriverLevelMoneyType.ticheng)) {//比例
                                            BigDecimal tcMoney = _money
                                                .multiply(dlmd.getCommission())
                                                .divide(new BigDecimal(100));
                                            companyMoney = companyMoney.add(tcMoney);
                                        }
                                    }
                                }
                            }

                            if (realCash.compareTo(companyMoney) == -1) {
                                companyMoney = realCash;
                                money = BigDecimal.ZERO;
                                sbmemo.append("金额不足，公司实际提成" + companyMoney + "元。");
                            } else {
                                money = realCash.subtract(companyMoney);
                            }

                            employProfit = money;
                            companyProfit = companyMoney;

                            driver.setVirtual(driver.getVirtual().add(money));
                            driverMapper
                                .updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

                            DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                            driverPaymentsRecord.setMoney(money);
                            driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                            driverPaymentsRecord
                                .setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_ORDER);
                            driverPaymentsRecord.setDriverId(driver.getId());
                            driverPaymentsRecord.setDriverRealName(driver.getRealname());
                            driverPaymentsRecord.setDriverUserName(driver.getUsername());
                            driverPaymentsRecord.setDriverPhone(driver.getPhone());
                            driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                            driverPaymentsRecord.setOrderId(order.getId());
                            driverPaymentsRecord.setOrderNumber(order.getOrderNo());
                            driverPaymentsRecord
                                .setOrderType(DriverPaymentsRecord.ORDER_TYPE_FREIGHT);
                            driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                            driverPaymentsRecord.setMemo(sbmemo.toString());
                            driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                            driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                            driverPaymentsRecord.setHappend(new Date());
                            driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                            //公司财务
                            String companyMemo =
                                "订单号【<a target='_blank' href='/freight/orderDetails/" + order
                                    .getId() + "'>" + order.getOrderNo() + "</a>】收入。";

                            Company company = companyMapper
                                .selectByPrimaryKey(driver.getCompanyId());
                            Company orderCompany = companyMapper
                                .selectByPrimaryKey(order.getCompanyId());

                            FinancialRecord financialRecord = new FinancialRecord();
                            StringBuilder sb = new StringBuilder();
                            sb.append(OrderNumberConfig.FINANCIAL_ORDER);//订单金额
                            sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);//对象 客户
                            sb.append(format.format(new Date()));//年月日时间
                            sb.append(OrderNumberConfig
                                .padZero(financialRecordMapper.getRunningNumber() + 1));//流水号
                            financialRecord.setCode(sb.toString());
                            financialRecord.setCompanyId(company.getId());
                            financialRecord.setCompanyName(company.getAbbreviation());
                            financialRecord.setOrderCompanyId(orderCompany.getId());
                            financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                            financialRecord.setMemo(companyMemo + driverPaymentsRecord.getMemo());
                            financialRecord.setMoney(companyMoney);
                            financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                            financialRecord.setWho(order.getPassengerName());
                            financialRecord.setOrderId(order.getId());
                            financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                            financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_FREIGHT);
                            financialRecordMapper.insertRecord(financialRecord);

                        } else {
                            companyGetAll = true;
                        }

                    } else {
                        companyGetAll = true;
                    }
                } else {
                    companyGetAll = true;
                }

                //公司得全部
                if (companyGetAll) {

                    companyProfit = realCash;

                    String companyMemo =
                        "订单号【<a target='_blank' href='/freight/orderDetails/" + order.getId() + "'>"
                            + order.getOrderNo() + "</a>】收入。";

                    Company company = companyMapper.selectByPrimaryKey(driver.getCompanyId());
                    Company orderCompany = companyMapper.selectByPrimaryKey(order.getCompanyId());

                    FinancialRecord financialRecord = new FinancialRecord();
                    StringBuilder sb = new StringBuilder();
                    sb.append(OrderNumberConfig.FINANCIAL_ORDER);//订单金额
                    sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);//对象 客户
                    sb.append(format.format(new Date()));//年月日时间
                    sb.append(OrderNumberConfig
                        .padZero(financialRecordMapper.getRunningNumber() + 1));//流水号
                    financialRecord.setCode(sb.toString());
                    financialRecord.setCompanyId(company.getId());
                    financialRecord.setCompanyName(company.getAbbreviation());
                    financialRecord.setOrderCompanyId(orderCompany.getId());
                    financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                    financialRecord.setMemo(companyMemo + sbmemo.toString());
                    financialRecord.setMoney(realCash);
                    financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                    financialRecord.setWho(order.getPassengerName());
                    financialRecord.setOrderId(order.getId());
                    financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                    financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_FREIGHT);
                    financialRecordMapper.insertRecord(financialRecord);
                }

            }

            if (null != driver) {
                //过路费
                BigDecimal fee = order.getGuoluMoney();
                if (fee.doubleValue() > 0) {
                    driver.setVirtual(driver.getVirtual().add(fee));
                    driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                    driverPaymentsRecord.setMoney(fee);
                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                    driverPaymentsRecord
                        .setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_ORDER_GUOLU);
                    driverPaymentsRecord.setDriverId(driver.getId());
                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                    driverPaymentsRecord.setOrderId(order.getId());
                    driverPaymentsRecord.setOrderNumber(order.getOrderNo());
                    driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_FREIGHT);
                    driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                    driverPaymentsRecord.setMemo(
                        "订单号【<a target='_blank' href='/freight/orderDetails/" + order.getId() + "'>"
                            + order.getOrderNo() + "</a>】过路费");
                    driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                    driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                    driverPaymentsRecord.setHappend(new Date());
                    driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                }

                if (setting.getInfoFeeFreight() != 0) {
                    if (null != setting.getInfoFeeType() && setting.getInfoFeeType()
                        .equals(InfoFeeType.finishTask)) {
                        driver.setVirtual(driver.getVirtual()
                            .subtract(new BigDecimal(setting.getInfoFeeFreight())));
                        driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                        //扣费记录
                        DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                        driverPaymentsRecord.setMoney(new BigDecimal(setting.getInfoFeeFreight()));
                        driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                        driverPaymentsRecord
                            .setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                        driverPaymentsRecord.setDriverId(driver.getId());
                        driverPaymentsRecord.setDriverRealName(driver.getRealname());
                        driverPaymentsRecord.setDriverUserName(driver.getUsername());
                        driverPaymentsRecord.setDriverPhone(driver.getPhone());
                        driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                        driverPaymentsRecord.setOrderId(order.getId());
                        driverPaymentsRecord.setOrderNumber(order.getOrderNo());
                        driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_FREIGHT);
                        driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                        driverPaymentsRecord
                            .setMemo("扣除公司所得保险费/信息费" + setting.getInfoFeeFreight() + "元。");
                        driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                        driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                        driverPaymentsRecord.setHappend(new Date());
                        driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                        //财务记录（保险费）
                        Company mainCompany = companyMapper.selectMainCompany();
                        DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                        FinancialRecord financialRecord = new FinancialRecord();
                        StringBuilder sb_f = new StringBuilder();
                        sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);//保险费
                        sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);//对象 服务人员
                        sb_f.append(format_f.format(new Date()));//年月日时间
                        sb_f.append(OrderNumberConfig
                            .padZero(financialRecordMapper.getRunningNumber() + 1));//流水号
                        financialRecord.setCode(sb_f.toString());
                        financialRecord.setCompanyId(mainCompany.getId());
                        financialRecord.setCompanyName(mainCompany.getAbbreviation());
                        financialRecord.setOrderCompanyId(mainCompany.getId());
                        financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                        financialRecord.setMemo(
                            "订单号【<a target='_blank' href='/freight/orderDetails/" + order.getId()
                                + "'>" + order.getOrderNo() + "</a>】保险费/信息费");
                        financialRecord.setMoney(new BigDecimal(setting.getInfoFeeFreight()));
                        financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                        financialRecord.setWho(driver.getRealname());
                        financialRecord.setOrderId(order.getId());
                        financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                        financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_FREIGHT);
                        financialRecordMapper.insertRecord(financialRecord);

                    }
                }

            }

            //更新订单
            Map<String, String> kv = new HashMap<String, String>();
            StringBuilder sb = new StringBuilder(freightApi.getFreightBaseURL())
                .append(FreightApi.FINISH_TASK).append("?appKey={appKey}");
            kv.put("orderId", String.valueOf(order.getId()));
            sb.append("&orderId={orderId}");
            if (null != order.getAfterPayTypeDetail()) {
                kv.put("afterPayTypeDetail", order.getAfterPayTypeDetail().toString());
                sb.append("&afterPayTypeDetail={afterPayTypeDetail}");
            }
            if (order.getCashMoney() != null) {
                kv.put("cashMoney", String.valueOf(order.getCashMoney()));
                sb.append("&cashMoney={cashMoney}");
            }
            if (order.getSignMoney() != null) {
                kv.put("signMoney", String.valueOf(order.getSignMoney()));
                sb.append("&signMoney={signMoney}");
            }
            if (order.getBalanceMoney() != null) {
                kv.put("balanceMoney", String.valueOf(order.getBalanceMoney()));
                sb.append("&balanceMoney={balanceMoney}");
            }
            if (order.getAlipayMoney() != null) {
                kv.put("alipayMoney", String.valueOf(order.getAlipayMoney()));
                sb.append("&alipayMoney={alipayMoney}");
            }
            if (order.getWeixinMoney() != null) {
                kv.put("weixinMoney", String.valueOf(order.getWeixinMoney()));
                sb.append("&weixinMoney={weixinMoney}");
            }
            if (order.getUnionpayMoney() != null) {
                kv.put("unionpayMoney", String.valueOf(order.getUnionpayMoney()));
                sb.append("&unionpayMoney={unionpayMoney}");
            }
            kv.put("companyProfit", companyProfit.toString());
            sb.append("&companyProfit={companyProfit}");
            kv.put("employProfit", employProfit.toString());
            sb.append("&employProfit={employProfit}");
            String resultStr = freightApi.post(sb.toString(), kv, setting);
            if (StringUtils.isNotBlank(resultStr)) {
                JSONObject jo = new JSONObject(resultStr);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    result.setSuccess(true);

                    //结算成功保存首单免费客户信息
                    FirstOrderPassenger firstOrderPassenger = new FirstOrderPassenger();
                    firstOrderPassenger.setPassengerId(passenger.getId());
                    firstOrderPassenger.setType(FirstOrderPassenger.FREE_ORDERTYPE_FREIGHT);
                    firstOrderPassengerMapper.insertRecord(firstOrderPassenger);

                    if (driver != null) {
                        freightApi.updateCarStatus(driver.getTruckId(), driver.getId(),
                            driver.getRealname() + " " + driver.getPhone(), 0, setting);
                    }

                    ReactorVo rVo = new ReactorVo();
                    rVo.setOrderChannelName(order.getChannelName());
                    rVo.setOrderType(OrderType.freight);
                    rVo.setPassenger(passenger);
                    rVo.setActivityEvent(ActivityEvent.orderCompleteTimes);
                    ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
                    applicationEventMulticaster.multicastEvent(activityCheckEvent);

                    //结算短信
                    FreightOrderFinishEvent freightOrderFinishEvent = new FreightOrderFinishEvent(
                        order);
                    applicationEventMulticaster.multicastEvent(freightOrderFinishEvent);

                } else {
                    String message = jo.getString("message");
                    result.setSuccess(false);
                    result.setMessage(message);
                }

            } else {
                result.setSuccess(false);
                result.setMessage("内部服务器错误");
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("内部服务器错误");
        }

        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<PayRecordOrder> createPayRecordOrder(PayRecordOrder payRecordOrder) {
        Result<PayRecordOrder> result = new Result<PayRecordOrder>();

        Map<String, String> kv = new HashMap<String, String>();
        StringBuilder sb = new StringBuilder(freightApi.getFreightBaseURL())
            .append(FreightApi.CREATE_PAYRECORDORDER).append("?appKey={appKey}");
        kv.put("orderId", String.valueOf(payRecordOrder.getOrderId()));
        sb.append("&orderId={orderId}");
        kv.put("money", payRecordOrder.getMoney().toString());
        sb.append("&money={money}");
        kv.put("payRecordTypeOrder", payRecordOrder.getPayRecordTypeOrder().toString());
        sb.append("&payRecordTypeOrder={payRecordTypeOrder}");
        String resultStr = freightApi.post(sb.toString(), kv, settingUtils.get());
        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                PayRecordOrder pr = gson.fromJson(data.toString(), PayRecordOrder.class);
                result.setResult(pr);
                result.setSuccess(true);
            } else {
                String message = jo.getString("message");
                result.setSuccess(false);
                result.setMessage(message);
            }
        } else {
            result.setSuccess(false);
            result.setMessage("未知错误");
        }

        return result;
    }


    @Override
    public PayRecordOrder findOnePayRecordOrder(Long id) {
        PayRecordOrder payRecordOrder = null;
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.QUERY_PAYRECORDORDER_ONE)
            .append("?id={id}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("id", String.valueOf(id));
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                payRecordOrder = gson.fromJson(data.toString(), PayRecordOrder.class);
            }
        }
        return payRecordOrder;
    }

    @Override
    public Result<PayRecordOrder> payRecordOrderTreatment(PayRecordOrder payRecordOrder) {

        Result<PayRecordOrder> result = new Result<PayRecordOrder>();

        StringBuilder sb = new StringBuilder();
        sb.append(freightApi.getFreightBaseURL()).append(FreightApi.TREATMENT_PAYRECORDORDER)
            .append("?id={id}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("id", String.valueOf(payRecordOrder.getId()));

        String resultStr = freightApi.put(sb.toString(), kv, settingUtils.get());
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            String message = jo.getString("message");
            result.setMessage(message);
            result.setSuccess(false);
        } else {
            result.setSuccess(true);
        }

        return result;
    }

    @Override
    public Long countFinishedByPassengerAndFinishTime(Long passengerId, String orderFromSources,
        Date startDate, Date endDate) {

        return freightApi
            .countFinishedByPassengerAndFinishTime(passengerId, orderFromSources, startDate,
                endDate, settingUtils.get());

    }

    @Override
    public OrderOrbit findOrbitByOrderId(Long id) {
        OrderOrbit orderOrbit = new OrderOrbit();
        try {

            StringBuilder builder = new StringBuilder();
            builder.append(freightApi.getFreightBaseURL()).append(FreightApi.QUERY_ORDERORBIT)
                .append("?orderId={orderId}&appKey={appKey}");
            Map<String, String> kv = new HashMap<String, String>();
            kv.put("orderId", String.valueOf(id));
            String result = freightApi.get(builder.toString(), kv, settingUtils.get());
            if (null != result) {
                JSONObject jo = new JSONObject(result);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    JSONObject data = jo.getJSONObject("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    ;
                    orderOrbit = gson.fromJson(data.toString(), OrderOrbit.class);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return orderOrbit;
    }

    @Override
    public List<Truck> findTruckByTruckTypeId(Long truckTypeId) {
        List<Truck> list = new ArrayList<Truck>();
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("freight")) {
            StringBuilder builder = new StringBuilder();
            builder.append(freightApi.getFreightBaseURL()).append(FreightApi.QUERY_PARAMS_TRUCKS)
                .append("?appKey={appKey}");

            Map<String, String> kv = new HashMap<String, String>();
            if (truckTypeId != null && truckTypeId != 0) {
                kv.put("truckTypeId", String.valueOf(truckTypeId));
                builder.append("&truckTypeId={truckTypeId}");
            }
            String result = freightApi.get(builder.toString(), kv, settingUtils.get());

            if (null != result) {
                JSONObject jo = new JSONObject(result);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    JSONObject data = jo.getJSONObject("data");
                    JSONArray ja = data.getJSONArray("rows");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    ;
                    list = gson.fromJson(ja.toString(), new TypeToken<List<Truck>>() {
                    }.getType());
                }
            }
        }
        return list;
    }

    @Override
    public List<Order> findByStatus(Integer orderStatusPaidan) {
        List<Order> list = new ArrayList<Order>();

        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.QUERY_ORDER)
            .append("?appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("status", String.valueOf(orderStatusPaidan));
        builder.append("&status={status}");
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                list = gson.fromJson(ja.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
        }
        return list;

    }

    @Override
    public void revoke(Order order, String string) {
        Result<Order> result = new Result<Order>();
        result.setSuccess(false);
        StringBuilder sb = new StringBuilder();
        sb.append(freightApi.getFreightBaseURL()).append(FreightApi.CALLBACK)
            .append("?appKey={appKey}");
        sb.append("&orderId={orderId}");
        sb.append("&action={action}");
        sb.append("&operator={operator}");
        sb.append("&cause={cause}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("orderId", String.valueOf(order.getId()));
        kv.put("action", "callback");
        kv.put("cause", string);
        kv.put("operator", "系统");
        String resultStr = freightApi.put(sb.toString(), kv, settingUtils.get());
        if (StringUtils.isBlank(resultStr)) {
            result.setSuccess(true);
            result.setMessage("收回订单成功");
            Driver driver = driverService.findOne(order.getEmployId());
            if (null != driver) {
                if (driver.getStatus() != Driver.DRIVER_OFFLINE) {
                    driverService
                        .updateStatusAndJobStatus(Driver.DRIVER_ONLINE, null, driver.getId());
                }
                FreightOrderCallBackEvent callBackEvent = new FreightOrderCallBackEvent(order,
                    driver);
                applicationEventMulticaster.multicastEvent(callBackEvent);
            }
        } else {
            result.setSuccess(false);
            result.setMessage("收回订单失败");
        }
    }

    @Override
    public long countActiveByPassenger(Long passengerId) {
        return freightApi.countActiveByPassenger(passengerId, settingUtils.get());
    }

    @Override
    public Map<String, Object> findRate(Long driverid, Integer page, Integer limit) {
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.QUERY_ORDEREVIEW)
            .append("?appKey={appKey}&page={page}&rows={rows}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));
        if (driverid != null) {
            kv.put("driverId", driverid + "");
            builder.append("&driverId={driverId}");
        }
        List<OrderReview> list = new ArrayList<OrderReview>();
        long total = 0;
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                list = gson.fromJson(ja.toString(), new TypeToken<List<OrderReview>>() {
                }.getType());
            }
        }
        List<Rate> data = new LinkedList<Rate>();
        for (OrderReview or : list) {
            Rate r = new Rate();
            r.setContent(or.getContent());
            r.setCreated(or.getCreated());
            r.setDriverId(or.getEmployId());
            r.setDriverName(or.getEmployName());
            r.setId(or.getId());
            r.setManager(false);
            r.setMemberId(or.getPassengerId());
            r.setMemberName(or.getPassengerName());
            r.setOrderId(or.getOrderId());
            r.setOrderNumber(or.getOrderNo());
            r.setStarLevel(or.getScore().floatValue());
            r.setUpdated(or.getUpdated());
            data.add(r);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("total", total);
        map.put("data", data);
        return map;
    }

    @Override
    public Rate findRateOne(Long id) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.QUERY_ORDEREVIEW_ONE)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (id != null) {
            kv.put("id", id + "");
            builder.append("&id={id}");
        }
        OrderReview or = null;
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                or = gson.fromJson(data.toString(), new TypeToken<OrderReview>() {
                }.getType());
            }
        }
        Rate r = null;
        if (or != null) {
            r = new Rate();
            r.setContent(or.getContent());
            r.setCreated(or.getCreated());
            r.setDriverId(or.getEmployId());
            r.setDriverName(or.getEmployName());
            r.setId(or.getId());
            r.setManager(false);
            r.setMemberId(or.getPassengerId());
            r.setMemberName(or.getPassengerName());
            r.setOrderId(or.getOrderId());
            r.setOrderNumber(or.getOrderNo());
            r.setStarLevel(or.getScore().floatValue());
            r.setUpdated(or.getUpdated());
        }
        return r;
    }

    @Override
    public void deleteRateOne(Long id) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.DELETE_ORDEREVIEW)
            .append("?appKey={appKey}");
        Map<String, String> kv = new LinkedHashMap<String, String>();
        if (id != null) {
            kv.put("id", id + "");
            builder.append("&id={id}");
        }
        OrderReview or = null;
        String result = freightApi.post(builder.toString(), kv, settingUtils.get());
        if (null != result) {
        }


    }

    @Override
    public List<Order> findOrderFinishedBycompanyId(Long companyId,
        Date start, Date end) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.COMPANY_ORDERFINISHEDINFO)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (start != null) {
            builder.append("&startDate={startDate}");
            kv.put("startDate", start.getTime() + "");
        }
        if (end != null) {
            builder.append("&endDate={endDate}");
            kv.put("endDate", end.getTime() + "");
        }

        if (companyId != null) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        List<Order> orderFromSourceVos = null;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                orderFromSourceVos = gson.fromJson(data.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
        }

        return orderFromSourceVos;
    }

    @Override
    public long countNotPayByPassenger(Long passengerId) {

        Long notPayAmounts = 0L;

        try {
            StringBuilder builder = new StringBuilder();
            builder.append(freightApi.getFreightBaseURL())
                .append(FreightApi.COUNT_NOTPAY_BY_PASSENGER).append("?appKey={appKey}");
            Map<String, String> kv = new HashMap<String, String>();
            builder.append("&passengerId={passengerId}");
            kv.put("passengerId", String.valueOf(passengerId));
            String result = freightApi.get(builder.toString(), kv, settingUtils.get());
            if (null != result) {
                JSONObject jo = new JSONObject(result);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    Long data = jo.getLong("data");
                    notPayAmounts = data;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return notPayAmounts;
    }

    @Override
    public Page<Order> findByDriverAndFinishTime(Long employId, Date start,
        Date end, Integer page, Integer limit) {

        Pageable pageable = new PageRequest(page, limit);

        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.QUERY_FINISHED_BY_EMPLOY)
            .append("?appKey={appKey}&page={page}&rows={rows}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(page + 1));
        kv.put("rows", String.valueOf(limit));

        kv.put("employId", String.valueOf(employId));
        builder.append("&employId={employId}");

        if (null != start) {
            kv.put("start", String.valueOf(start.getTime()));
            builder.append("&start={start}");
        }
        if (null != end) {
            kv.put("end", String.valueOf(end.getTime()));
            builder.append("&end={end}");
        }

        List<Order> list = new ArrayList<Order>();
        long total = 0;
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                list = gson.fromJson(ja.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
        }
        return new PageImpl<Order>(list, pageable, total);
    }

    @Override
    public List<Order> findReward(Long driverId, BigDecimal lowestMoney, Date start, Date end) {
        List<Order> list = new ArrayList<Order>();

        try {
            StringBuilder builder = new StringBuilder();
            builder.append(freightApi.getFreightBaseURL()).append(FreightApi.FIND_REWARD)
                .append("?appKey={appKey}");
            Map<String, String> kv = new HashMap<String, String>();

            builder.append("&employId={employId}");
            kv.put("employId", String.valueOf(driverId));

            builder.append("&money={money}");
            kv.put("money", String.valueOf(lowestMoney));

            if (null != start) {
                builder.append("&startTime={startTime}");
                kv.put("startTime", String.valueOf(start.getTime()));
            }

            if (null != end) {
                builder.append("&endTime={endTime}");
                kv.put("endTime", String.valueOf(end.getTime()));
            }

            String result = freightApi.get(builder.toString(), kv, settingUtils.get());
            if (null != result) {
                JSONObject jo = new JSONObject(result);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    JSONArray data = jo.getJSONArray("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    ;
                    list = gson.fromJson(data.toString(), new TypeToken<List<Order>>() {
                    }.getType());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

    @Override
    public Result<TruckType> newCreateTruckType(TruckType truckType) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.NEW_CREATE_TRUCKTYPE)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        builder.append("&typeName={typeName}");
        builder.append("&len={len}");
        builder.append("&width={width}");
        builder.append("&height={height}");
        builder.append("&carryingCapacity={carryingCapacity}");
        builder.append("&cangointotown={cangointotown}");
        builder.append("&sequence={sequence}");
        builder.append("&img={img}");
        kv.put("typeName", truckType.getTypeName());
        kv.put("len", String.valueOf(truckType.getLen()));
        kv.put("width", String.valueOf(truckType.getWidth()));
        kv.put("height", String.valueOf(truckType.getHeight()));
        kv.put("carryingCapacity", String.valueOf(truckType.getCarryingCapacity()));
        kv.put("cangointotown", String.valueOf(truckType.getCangointotown()));
        kv.put("sequence", String.valueOf(truckType.getSequence()));
        kv.put("img", truckType.getImg());
        String result = freightApi.post(builder.toString(), kv, settingUtils.get());
        Result<TruckType> resultTruckType = new Result<TruckType>();
        if (result != null) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                truckType = gson.fromJson(data.toString(), new TypeToken<TruckType>() {
                }.getType());
                resultTruckType.setResult(truckType);
                resultTruckType.setSuccess(true);
                resultTruckType.setMessage("创建货车类型成功");
            } else {
                resultTruckType.setSuccess(false);
                String msg = jo.getString("message");
                resultTruckType
                    .setMessage(msg.split(":").length > 1 ? msg.split(":")[1] : msg.split(":")[0]);
            }
        }
        return resultTruckType;
    }

    @Override
    public String newUpdateTruckType(Long truckTypeId, String typeName, Double len, Double width,
        Double height, Double carryingCapacity, Integer sequence, Boolean cangointotown,
        String img) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.NEW_UPDATE_TRUCKTYPE)
            .append("?appKey={appKey}&truckTypeId={truckTypeId}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("truckTypeId", String.valueOf(truckTypeId));
        if (StringUtils.isNotBlank(typeName)) {
            builder.append("&typeName={typeName}");
            kv.put("typeName", typeName);
        }
        if (len != null) {
            builder.append("&len={len}");
            kv.put("len", String.valueOf(len));
        }
        if (width != null) {
            builder.append("&width={width}");
            kv.put("width", String.valueOf(width));
        }
        if (height != null) {
            builder.append("&height={height}");
            kv.put("height", String.valueOf(height));
        }
        if (carryingCapacity != null) {
            builder.append("&carryingCapacity={carryingCapacity}");
            kv.put("carryingCapacity", String.valueOf(carryingCapacity));
        }
        if (sequence != null) {
            builder.append("&sequence={sequence}");
            kv.put("sequence", String.valueOf(sequence));
        }
        if (cangointotown != null) {
            builder.append("&cangointotown={cangointotown}");
            kv.put("cangointotown", String.valueOf(cangointotown));
        }
        if (img != null) {
            builder.append("&img={img}");
            kv.put("img", img);
        }
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        String message = null;
        if (result != null) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                message = "修改成功";
            } else {
                message = jo.getString("message");
            }
        }
        return message;
    }

    @Override
    public Result<TruckType> subscribeTruckType(TruckTypeCompany ttc) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.SUBSCRIBETRUCKTYPE)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        builder.append("&truckTypeId={truckTypeId}");
        builder.append("&companyId={companyId}");
        builder.append("&companyName={companyName}");
        builder.append("&areaId={areaId}");
        kv.put("truckTypeId", ttc.getTruckTypeId() + "");
        kv.put("companyId", ttc.getCompanyId() + "");
        kv.put("companyName", ttc.getCompanyName());
        kv.put("areaId", ttc.getAreaId() + "");
        String result = freightApi.post(builder.toString(), kv, settingUtils.get());
        Result<TruckType> resultTruckType = new Result<TruckType>();
        if (result != null) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                resultTruckType.setSuccess(true);
                resultTruckType.setMessage("开通成功");
            } else {
                resultTruckType.setSuccess(false);
                String msg = jo.getString("message");
                resultTruckType
                    .setMessage(msg.split(":").length > 1 ? msg.split(":")[1] : msg.split(":")[0]);
            }
        }
        return resultTruckType;
    }

    @Override
    public Page<TruckTypeCompany> queryTruckTypeCompany(Long truckTypeId, Long companyId,
        String companyName) {
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        List<TruckTypeCompany> list = new ArrayList<TruckTypeCompany>();
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL());
        builder.append(FreightApi.QUERY_TRUCKTYPECOMPANY);
        builder.append("?truckTypeId={truckTypeId}&appKey={appKey}&page={page}&rows={rows}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("truckTypeId", String.valueOf(truckTypeId));

        if (StringUtils.isNotBlank(companyName)) {
            kv.put("companyName", companyName);
            builder.append("&companyName={companyName}");
        }
        if (companyId != null) {
            kv.put("companyId", String.valueOf(companyId));
            builder.append("&companyId={companyId}");
        }
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));

        String result = freightApi.get(builder.toString(), kv, settingUtils.get());

        long total = 0;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                JSONArray rows = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(rows.toString(), new TypeToken<List<TruckTypeCompany>>() {
                }.getType());
                for (TruckTypeCompany ttc : list) {
                    ttc.setArea(areaMapper.selectByPrimaryKey(ttc.getAreaId()));
                }

                total = data.getLong("total");
            }
        }
        return new PageImpl<TruckTypeCompany>(list, pageable, total);
    }

    @Override
    public Map<String, Object> updateTruckTypeCompany(Long id, Long areaId) {
        Map<String, Object> map = new HashMap<String, Object>();

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("id", id + "");
        kv.add("areaId", areaId + "");
        String result = freightApi
            .post(freightApi.getFreightBaseURL() + FreightApi.UPDATE_TRUCKTYPE_COMPANY_AREA, kv,
                settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("success", true);
            map.put("message", "修改成功!");
        } else {
            String message = jo.getString("message");
            map.put("success", false);
            map.put("message", message);
        }
        return map;
    }

    @Override
    public Map<String, Object> deleteTruckTypeCompany(Long truckTypeCompanyId) {
        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("truckTypeCompanyId", truckTypeCompanyId + "");
        String result = freightApi
            .post(freightApi.getFreightBaseURL() + FreightApi.CANCEL_TRUCKTYPE_COMPANY, kv,
                settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("success", true);
            map.put("message", "取消成功");
        } else {
            String message = jo.getString("message");
            map.put("success", false);
            map.put("message", message);
        }
        return map;
    }

    @Override
    public Result<Order> createMore(Order order, String waypoint) {
        Result<Order> result = new Result<Order>();
        StringBuilder builder = new StringBuilder(freightApi.getFreightBaseURL());
        builder.append(FreightApi.ADDMORE);

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("passengerId", String.valueOf(order.getPassengerId()));
        if (StringUtils.isNotBlank(order.getPassengerName())) {
            kv.add("passengerName", order.getPassengerName());
        }
        kv.add("passengerPhone", order.getPassengerPhone());
        kv.add("channelName", order.getChannelName());
        kv.add("startTime", String.valueOf(order.getStartTime().getTime()));
        if (StringUtils.isNotBlank(order.getMemo())) {
            kv.add("memo", order.getMemo());
        }
        if (null != order.getFlitting()) {
            kv.add("flitting", String.valueOf(order.getFlitting()));
        }
        if (null != order.getReceipt()) {
            kv.add("receipt", String.valueOf(order.getReceipt()));
        }
        if (null != order.getReceivedPay()) {
            kv.add("receivedPay", String.valueOf(order.getReceivedPay()));
        }
        if (null != order.getPayMount()) {
            kv.add("payMount", String.valueOf(order.getPayMount()));
        }
        if (StringUtils.isNotBlank(waypoint)) {
            kv.add("waypoint", waypoint);
        }
        kv.add("employId", String.valueOf(order.getEmployId()));
        kv.add("employName", order.getEmployName());
        kv.add("employPhone", order.getEmployPhone());
        kv.add("employCompanyId", String.valueOf(order.getEmployCompanyId()));
        kv.add("employNo", order.getEmployNo());
        if (StringUtils.isNotBlank(order.getEmployPhoto())) {
            kv.add("employPhoto", order.getEmployPhoto());
        }
        if (null != order.getEmployScore()) {
            kv.add("employScore", String.valueOf(order.getEmployScore()));
        }
        if (null != order.getBudgetPay()) {
            kv.add("budgetPay", String.valueOf(order.getBudgetPay()));
        }
        String resultStr = freightApi.postMultiValueMap(builder.toString(), kv, settingUtils.get());
        JSONObject jo = new JSONObject(resultStr);
        Integer code = jo.getInt("code");
        if (code == 0) {
            result.setSuccess(true);
            JSONObject data = jo.getJSONObject("data");
            Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
            order = gson.fromJson(data.toString(), Order.class);
            result.setResult(order);
            result.setMessage(jo.getString("message"));
        } else {
            result.setSuccess(false);
        }

        return result;
    }

    @Override
    public TruckType findTruckByTruckTypeIdAndCompanyId(Long truckTypeId, Long companyId) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.NEW_QUERY_ONE_TRUCKTYPE)
            .append(".json?appKey={appKey}&truckTypeId={truckTypeId}&companyId={companyId}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("truckTypeId", String.valueOf(truckTypeId));
        kv.put("companyId", String.valueOf(companyId));
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        TruckType truckType = null;
        if (result != null) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                truckType = gson.fromJson(data.toString(), new TypeToken<TruckType>() {
                }.getType());
                Area area = areaMapper.selectByPrimaryKeyWithCharge(truckType.getAreaId());
                if (area != null) {
                    truckType.setAreaName(area.getName());
                }
            }
        }
        return truckType;
    }

    @Override
    public PageVo<DriverOrderDetailVo> driverOrderDetailCount(Long driverId, Date start, Date end) {
        StringBuilder builder = new StringBuilder();
        builder.append(freightApi.getFreightBaseURL()).append(FreightApi.DRIVERORDERDETAILCOUNT)
            .append(".json?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (driverId != null) {
            kv.put("driverId", driverId + "");
            builder.append("&driverId={driverId}");
        }
        if (start != null) {
            kv.put("startDate", start.getTime() + "");
            builder.append("&startDate={startDate}");
        }
        if (end != null) {
            kv.put("endDate", end.getTime() + "");
            builder.append("&endDate={endDate}");
        }
        String result = freightApi.get(builder.toString(), kv, settingUtils.get());
        PageVo<DriverOrderDetailVo> page = new PageVo<DriverOrderDetailVo>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                page.setTotalElements(jo.optLong("data", 0L));
            }
        }

        return page;
    }

    @Override
    public Result<Order> updateRealMoney(Order order, BigDecimal couponMoney, BigDecimal cashMoney,
        BigDecimal signMoney, BigDecimal balanceMoney, BigDecimal alipayMoney,
        BigDecimal weixinMoney,
        BigDecimal driverMoney, BigDecimal memberMoney, BigDecimal wxMoney, String content) {
        Result<Order> result = new Result<Order>();
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();
        String operator = principal.getUsername();
        if (null == couponMoney) {
            couponMoney = BigDecimal.ZERO;
        }
        if (null == cashMoney) {
            cashMoney = BigDecimal.ZERO;
        }
        if (null == signMoney) {
            signMoney = BigDecimal.ZERO;
        }
        if (null == balanceMoney) {
            balanceMoney = BigDecimal.ZERO;
        }
        if (null == alipayMoney) {
            alipayMoney = BigDecimal.ZERO;
        }
        if (null == weixinMoney) {
            weixinMoney = BigDecimal.ZERO;
        }

        final BigDecimal newCash = couponMoney.add(cashMoney).add(signMoney).add(balanceMoney)
            .add(alipayMoney).add(weixinMoney);

        StringBuilder sb = new StringBuilder();
        sb.append(freightApi.getFreightBaseURL());
        sb.append(FreightApi.UPDATE_REALMONEY);

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("orderId", String.valueOf(order.getId()));
        kv.add("couponMoney", String.valueOf(couponMoney));
        kv.add("cashMoney", String.valueOf(newCash));
        kv.add("signMoney", String.valueOf(signMoney));
        kv.add("balanceMoney", String.valueOf(balanceMoney));
        kv.add("alipayMoney", String.valueOf(alipayMoney));
        kv.add("weixinMoney", String.valueOf(weixinMoney));
        kv.add("operator", operator);
        kv.add("content", content);

        freightApi.postMultiValueMap(sb.toString(), kv, settingUtils.get());

        Driver driver = driverMapper.selectByPrimaryKey(order.getEmployId());

        if (driverMoney.compareTo(BigDecimal.ZERO) != 0) {
            driver.setVirtual(driver.getVirtual().add(driverMoney));
            driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

            DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
            driverPaymentsRecord.setMoney(driverMoney);
            driverPaymentsRecord.setAfterMoney(driver.getVirtual());
            driverPaymentsRecord.setDriverId(driver.getId());
            driverPaymentsRecord.setDriverRealName(driver.getRealname());
            driverPaymentsRecord.setDriverUserName(driver.getUsername());
            driverPaymentsRecord.setDriverPhone(driver.getPhone());
            driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
            driverPaymentsRecord.setOrderId(order.getId());
            driverPaymentsRecord.setOrderNumber(order.getOrderNo());
            driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_FREIGHT);
            driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
            driverPaymentsRecord.setMemo(
                "【" + principal.getUsername() + "】将订单金额由￥" + order.getRealPay() + "修改为￥" + newCash
                    + "，原因：" + content + "，订单号【<a target='_blank' href='/freight/orderDetails/"
                    + order.getId() + "'>" + order.getOrderNo() + "</a>】");
            driverPaymentsRecord.setOperating(principal.getUsername());
            if (driverMoney.doubleValue() > 0) {
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_MODIFY);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
            } else {
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMED_TYPE_MODIFY);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
            }
            driverPaymentsRecord.setHappend(new Date());
            driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

        }
        if (memberMoney.compareTo(BigDecimal.ZERO) != 0) {
            Result<Passenger> result_p = passengerApi
                .findOnePassenger(order.getPassengerId(), settingUtils.get());
            Passenger passenger = result_p.getResult();

            if (null != passenger) {

                String memo =
                    "【" + principal.getUsername() + "】将订单金额由￥" + order.getRealPay() + "修改为￥"
                        + newCash + "，原因：" + content
                        + "，订单号【<a target='_blank' href='/freight/orderDetails/" + order.getId()
                        + "'>" + order.getOrderNo() + "</a>】";

                if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                    passengerApi.createPassengerAccount(passenger, null, memberMoney,
                        PassengerAccount.PayType.CASH_MODIFY, principal.getUsername(), memo,
                        order.getId(), order.getOrderNo(), PassengerAccount.ORDER_TYPE_FREIGHT,
                        null, true, false, settingUtils.get());
                } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                    Enterprise enterprise = passengerApi
                        .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get())
                        .getResult();
                    if (null != enterprise) {
                        passengerApi.createEnterpriseAccount(enterprise, memberMoney,
                            PassengerAccount.PayType.CASH_MODIFY, principal.getUsername(), memo,
                            order.getId(), order.getOrderNo(), PassengerAccount.ORDER_TYPE_FREIGHT,
                            null, true, false, settingUtils.get());
                    }
                }

            }
        }
        BigDecimal financialCash = driverMoney.multiply(new BigDecimal(-1));

        FinancialRecord financialRecord = financialRecordMapper
            .selectByOrderIdAndOrderType(order.getId(), FinancialRecord.FINANCIALRECORD_TYPE_SHOURU,
                FinancialRecord.ORDER_TYPE_FREIGHT);
        if (null != financialRecord) {
            BigDecimal oldMoney = financialRecord.getMoney();
            financialRecord.setMoney(financialRecord.getMoney().add(financialCash));
            financialRecord.setMemo(
                financialRecord.getMemo() + " ; " + "<br/>【" + principal.getUsername() + "】将订单金额由￥"
                    + order.getRealPay() + "修改为￥" + newCash + "，原因：" + content + "，修改前￥" + oldMoney
                    + "，修改后￥" + financialRecord.getMoney() + "");
            financialRecordMapper.updateByPrimaryKey(financialRecord);
        }
        final String clientPhone = order.getPassengerPhone();
        final String orderNumber = order.getOrderNo();
        final Long companyId = order.getCompanyId();
        Company orderCompany = companyMapper.selectByPrimaryKey(companyId);
        Company mainCompany = companyMapper.selectMainCompany();
        Setting setting = settingUtils.get();
        if (!mainCompany.getId().equals(orderCompany.getId()) && setting.isSmsMainCompany()) {
            orderCompany = mainCompany;
        }
        final Company finalCompany = orderCompany;

        try {
            SmsTemplet templet = smsService
                .findByAlias(finalCompany.getId(), SmsTemplet.SmsType.modifyFreightCash);

            if (null != templet && StringUtils.isNotBlank(templet.getContent())) {
                smsService.sendSms(clientPhone, "modifyFreightCash",
                    "{\"订单号\":\"" + "***" + orderNumber.substring(8) + "\",\"收费金额\":\"" + newCash
                        + "" + "\",\"投诉建议电话\":\"" + finalCompany.getTelephone() + "\"}",
                    finalCompany.getId(), 0, finalCompany.getSignName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        result.setSuccess(true);

        result.setMessage("修改金额成功");
        return result;
    }

    @Override
    public Long getCreateOrderNumber(Long passengerId, String appKey) {
        return freightApi.selectCreateOrderNumber(passengerId, appKey, settingUtils.get());
    }


}
